在实际工作中经常会涉及对字符串进行操作,
‘’ 单引号括起来的一个字符实际上代表一个整数
“”双引号括起来的表示字符串。
借助字符串操作函数,提高操作效率。
常用字符串操作函数,以及使用案例
字符串连接函数
strcat (str1,str2)
功能:将字符串2粘贴到字符串1后面。
字符串比较函数
字符串的长度可以通过strlen函数进行测算
#include<stdio.h>
#include<string.h>
int main()
{
char buf1[]="hello world";
char buf2[] =“hello world“;
char buf3[]="hello world\r\n"
int len1,len2,len3;
len1=strlen(buf1);
len2 =strlen (buf2);
len3 =strlen(buf3);
printf(”%d%d%d“,len1,len2,len3);
}
通过程序验证,可以发现空格在字符串中不占长度;
len1 = len2 =10; len3=12
/r 转义字符回车
/n 转义字符 换行。
不同的系统有所区别,在ubuntu下测试,空格计算在内,实验如下图所示。
wxl@wxl-virtual-machine:~$ cat ceshi.c
#include<stdio.h>
#include<string.h>
int main()
{
char buf1[]="hello world";
char buf2[]="hello world";
char buf3[]="hello world\r\n";
int len1,len2,len3;
len1=strlen(buf1);
len2=strlen(buf2);
len3 = strlen(buf3);
printf("%d\n%d\n%d",len1,len2,len3);
}
wxl@wxl-virtual-machine:~$ gcc ceshi.c
wxl@wxl-virtual-machine:~$ ./a.out
11
12
13wxl@wxl-virtual-machine:~$