1、字符串复制函数:strcpy(str1,str2)
- str1 接收字符串内容的字符数组名
- str2 所要复制的字符串常量或者字符数组名
- 使用该函数前必须包含头文件 string.h
#include<string.h>
#include<stdio.h>;
void main()
{
char schar[100],scopy[100];
puts("Please input the string:(Length<100)");
gets(schar);
strcpy(scopy,schar);
puts("Ok, the string is:");
puts(scopy);
strcpy(scopy,"miss you");
puts(scopy);
}
结果:
2、字符串的比较:strcmp(str1,str2)
- 如果两个字符数组存放的字符串完全相同,则返回 0
- 若不完全相同,则根据两个字符串中第一个不同的字符的差值,得出大于0的值或者小于0的值
- 所谓的差值,是用ASCII码值来做差运算的
#include<string.h>
#include<stdio.h>;
void main()
{
char name[100];
puts("Please input Your Name:");
gets(name);
int result;
if((result=strcmp(name,"xiaoxi"))==0)
{
puts("Hello,xiaoxi!");
}
else
{
puts("Can not log in");
}
}
结果:
3、字符串的长度:strlen(str)
- 该函数从字符串的起始位置开始检查,每增加一个字符,字符串长度就增加 1,直到所要计算的字符是 ‘\0’
- 字符 ‘\0’ 不计入字符串的长度
//字符串长度
#include<string.h>
#include<stdio.h>;
void main()
{
char schar[100];
int len;
puts("Please input the string:(Length<100)");
gets(schar);
puts("Ok, the string is:");
puts(schar);
schar[97]='b';
schar[98]='a';
puts(schar);
len = strlen(schar);
printf("schar[98] is %c\n",schar[98]);
printf("The length of schar is %d\n",len);
}
结果:
4、字符串的连接:strcat(str1,str2)
- str1 里面保存拼接好的字符串
- 将 str1 中字符串的最后一个字符 ‘\0’ 去掉,然后拼接上 str2 中字符串的内容,最后一个字符为 ‘\0’
- 如果第一个字符数组的长度不够长,一方面,第二个字符串的内容不能在第一个字符数组中完全保存,另一方面,第一个字符数组中保存的字符串没有结束符
#include<string.h>
#include<stdio.h>;
void main()
{
char str1[10],str2[20],str3[10];
puts("Please input the str1:");
gets(str1);
puts("Please input the str2:");
gets(str2);
puts("Please input the str3:");
gets(str3);
puts(strcat(str1,str2));
puts(strcat(str2,str3));
}
结果:因为第一个字符数组长度不够