北京大學C語言學習第三天

字符串1
所佔字節數爲 字符數加1 ,結尾有個\0,字符串長度不包括 \0。
字符串3種形式:
1.雙引號括起來的
2.存放於數組中的,以/0結尾
3.string對象

字符串常量: 空串(佔據一個字節空間,存放\0)
包含“\0” 字符的一維數組,就是一個字符串,存放的字符串由 “\0” 前的字符組成。
char 數組存放字符串,數組元素個數至少爲 字符串長度+1
char 數組的內容,初始化時可以設定。
printf讀入字符數組時,會在字符串的末尾自動加上 “\0”.
程序實例:

#include<iostream>
#include<cstring>
using namespace std;
int main(){
char title[]="Prison Break";
char hero[]="Michel Socfield";
char PrisonName[100];
char response[100];
cout<<"What's the name of the prison in "<<title<<endl;
cin>>PrisonName;
if(strcmp(PrisonNmame,"Fox-River")==0)
cout<<"Yeah ! do you love "<<hero<<endl;
else{
strcpy(response,"It seems you haven't watched it! \n");
cput<<response;
}
return 0;
}

a[3]=0; 等價於 a[3]=’\0’;
字符串2
scanf讀入字符串
在數組長度不變的情況下,scanf可能導致數組越界
讀入一行到字符數組:
1.cin.getline(char buf[],int bufsize);
code:

#include<iostream>
using namespace std;
int main(){
	char line[10];
	cin.getline(line,sizeof(line));//讀入最多9個字符到line
	cout<<line;
	return 0;
}

2.gets(char buf[]);讀入一行,自動添加“\0”
code:

char s[10];
while(gets(s)){
printf("%s\n",s);
}

讀入一行(行長度不超過bufsize-1)或bufsize-1個字符到buf,自動添加“\0”,回車換行符不會寫入buf,但是會從輸入流中去掉。

字符串3
字符串庫函數
#include
字符串函數都是根據\0 來判斷字符串結尾
形參爲 char[] 類型,則實參可以是char數組或字符串常量

1字符串拷貝:
strcpy(char [] dest,char [] src); //拷貝src到dest
2字符串比較小:
int strcmp(char [] s1,cahr [] s2);//返回0則相等
3求字符串長度:
int strlen(char [] s);
4字符串拼接:
strcat(char [] s1,char [] s2);//s2拼接到s1後面
5字符串轉成大寫:
strupr(char []);
6 字符串轉成小寫:
strlwr(char []);

字符串庫函數用法示列:
code:

#include<iostream>
#include<cstring>
using namespace std;
void PrintSmall(char s1[],char s2[]){//輸出字典序小的字符串
if(strcmp(s1,s2)<=0)
cout<<s1;
else cout<<s2;
}
int main(){
char s1[30];
char s2[40];
char s3[100];
strcpy(s1,"hello");
strcpy(s2,s1);
cout<<"1 "<<s2<<endl;
strcat(s1,"world");
cout<<"2 "<<s1<<endl;
cout<<"3 ";PrintSmall("abc",s2);cout<<endl; 
cout<<"4 ";PrintSmall("abc","aaa");cout<<endl;
cout<<"5 "<<","<<strlen("abc")<<endl;
strupr(s1);
cout<<"6 "<<s1<<endl;
return 0;
}

strlen 常見糟糕用法:
char s[100]=“test”;
for(int i=0;i<strlen(s);i++){//每次調用strlen這是在效率上最大的浪費
s[i]=s[i]+1; //訪問s[i]
}
以上把i<strlen 換爲 s[i] 是一樣的效果。

字符串4
編寫判斷字串的函數
code:

int Strstr(char s1[],char s2[]){
//尋找s1中是否含有字串s2
if(s2[0]==0) return 0;
for(int i=0;s1[i];i++){//枚舉比較起點
int k=0i,j=0;
for(;s2[j];++j;++k){
id(s1[k]!=s2[j])
break;
}
if(s2[j]==0) return i;
}
return -1;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章