下面是C语言中几种常用的字符串函数的基本使用方法,它们频繁的使用在各个C项目的开发中,属于C语言标准库函数。
目录
strcmp函数
字符串比较函数
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int ret;
char str1[]="hello"; //可以修改str1和str2的字符串的内容来验证
char str2[]="hello";
ret=strcmp(str1,str2);
printf("ret is =%d\n",ret);
return 0;
}
经过代码验证,我们发现当strcmp(str1,str2)时 如果str1和str2比较结果相同,返回0。如果str1>str2,返回正数。反之,返回负数。
strlen函数
计算字符串的长度,但是不包括结束符\0在内
#include<stdio.h>
#include<string.h>
int main()
{
int ret;
const char value[]="hello";
ret=strlen(value);
if(ret == 0){
printf("perror\n");
}
printf("strlen_len=:%d\n",ret);
printf("sizeof_len=:%d\n",sizeof(value));
return 0;
}
输出 strlen_len=:5 sizeof_len=:6 输出表明了strlen和sizeof函数的区别。sizeof函数会把字符串后面结束符的\0获取。
strcpy函数
字符串复制函数
把字符串abcdefg复制到array中,遇到'\0'停止。
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char array[20]="welcome,here";
const char msg[10]="abcdefg";
strcpy(array,msg);
printf("The new array is:%s\n",array);
return 0;
}
输出 The new array is:abcdefg 将字符串abcdefg直接复制到array中, welcome,here被覆盖。
strncpy函数
将一字符串的一部分复制到另一个 字符串中
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char array[20]="welcome,here";
const char msg[10]="abcdefg";
strncpy(array,msg,5);
printf("The new array is:%s\n",array);
return 0;
}
输出The new array is:abcdeme,here 复制了abcdefg的前5个字符到array中。
strcat函数
字符串连接
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char msg[20]="welcome";
char value[]="beijing";
strcat(msg,value);
printf("The new msg is:%s\n",msg);
return 0;
}
输出 The new msg is:welcomebeijing
strncat函数
将一字符串的一部分连接到另一个 字符串中
#include<stdio.h>
#include<string.h>
int main()
{
char value[10]="Bye Bye";
char msg[10]="hello";
char str1[10]={'1','2','3'};
char str2[5]={'x','y','z','w'};
strcat(str1,str2);
printf("The new str1 is:%s\n",str1);
//注意,这里的str1已经改变
strncat(str1,str2,2);
printf("The strncat str1 is:%s\n",str1);
strncat(msg,str2,3);
printf("The strncat msg is:%s\n",msg);
strncat(value,str2,sizeof(value)-strlen(value)-1);
printf("The new value is:%s\n",value);
return 0;
}