字符串比较函数
原型: int strcmp(char *str1, char *str2);
例子: if(strcmp(buf1,buf2)>0) printf("buffer 1 is greater than buffer 2.\n");
str1>str2,返回值 > 0(一般返回1),两串相等,返回0
字符串长度函数
原型: int strlen(const char *s);
例子: char *buf1="haha"; len=strlen(buf1); //len=4
查找字符串str2在str1第一次出现的位置
原型: char *strstr(char *str1, char *str2);
例子:
char *str1 = "She is prrety", *str2 = "he", *ptr;
ptr = strstr(str1, str2);
printf("The substring is: %s\n", ptr);
printf("The position is:%d\n",ptr-str1);
//输出:
//The substring is: he is prrety
//The position is:1
拷贝字符串
原型: char *strcpy(char *destin, char *source);
例子:
char string[10];
char *str1 = "abcdefghi";
strcpy(string, str1);
printf("%s\n", string);
//输出:
//abcdefghi
strncpy(string, str1,3);//string=str1的前三个字符
字符串拼接函数
原型: char *strcat(char *destin, char *source);
例子:
char str[25];
char *str1 ="I am", *str2 = " Lucy.";
strcpy(str,str1); //先复制str1的内容
strcat(str,str2); //再接上str2的内容
printf("%s\n", str);
//输出
//I am Lucy.
要注意的是,strcat的第一个参数只能是str这样定义的数组,不能是指针str1
查找字符在字符串的位置
原型: char *strchr(char *str, char c);
例子:
char string[15]="BUPT";
char *ptr, c = 'U';
ptr = strchr(string, c);
if (ptr)
printf("The character %c is at position: %d\n", c, ptr-string);
else
printf("The character was not found\n");
//输出:
//The character %c is at position: 1