编程中,常用到字符串的各个函数,总结如下:
1、字符串的初始化
1)char ch[5]={0}; //字符串,不是字符数组
2)char ch[5]={'\0'}; //字符串,不是字符数组,因为‘\0’与0等价。
3)char ch[5]=""; //字符串,不是字符数组
4)char *ch = ""; //很明显的字符串
2、字符串的复制
char ch[5];
char *str ="hao";
strcpy(ch,str);
3、字符串比较大小
char ch[]=“hello”;
char str[]="hello";
strcmp(ch,str);二者相等则返回0;ch小于str返回负值,ch大于str返回正值。
4、c++中的string与c语言中的字符串进行转换
1)string str= "hello";
const char *ch = c_str(str);
2)char *ch="hello";
std::string str(ch);//c++可以直接将c语言的字符串转化为string
std::string str=ch;
5、其他类型的数据与字符串的转换
char ch[]=“8000”;
1)int i=atoi(ch);
2)lont int j = atol(ch);
3)double f= atof(ch);
4)char str[2];
sprintf(str,"%d",100);//将数字100转换为十进制,再转化为字符串
sprintf(str,"%x",100);//将数字100转换为十六进制,再转化为字符串
6、字符串的长度
char str[3] = "ni";
strlen(str);//值为2,不包含‘\0’的所有字符的个数。