目录
在使用字符串函数时须在程序前面使用string函数,如
#include<string.h> //string---字符串,h(head)表示头文件
1.字符串连接函数strcat
其一般形式为
strcat(字符数组名1,字符数组名2)
其功能是:把字符数组2中的字符串连接到字符数组1中的字符串后面,同时删去字符串1后面的结束标志符'\0'。
一般打印“hello world!”使用的是标准输入输出函数stdio
#include <stdio.h>
int main()
{
printf("hello world!\n");
return 0;
}
而当我们使用strcat函数时,代码模板如下:
#include <stdio.h>
#include <string>
int main()
{
char str1[15] = "hello ",str2[] = "world!";
strcat(str1, str2); //将str2的内容加在了str1的后面
printf("%s", str1); //此时打印str1的结果就为 hello world!
return 0;
}
2.字符串复制函数strcpy
一般格式为:
strcpy(字符数组1,字符数组2)
其功能为:把字符数组2的内容复制给字符数组1中
例如
#include <stdio.h>
#include <string>
int main()
{
char str1[] = "hello", str2[] = "world";
strcpy(str1, str2); //表示运行之后“str1”的内容变为“world”
printf("%s", str1); //此时显示的结果为world
return 0;
}
3.字符串比较函数strcmp
一般形式为:
strcmp(字符数组名1,字符数组名2)
其功能是按照ASCII码顺序比较两个数组的字符串,并由函数返回值返回比较结果。
字符串1=字符串2,返回值为0;
字符串1>字符串2,返回值为正数;
字符串1<字符串2,返回值为负数;
同时改函数也可以比较两个字符常量或比较数组和字符常量。
例如,比较下列两个数组的字符串
#include <stdio.h>
#include <string>
int main()
{
int a;
char str1[15] = "hello ",str2[] = "world!";
a=strcmp(str1, str2);
if (a > 0)
printf("str1>str2\n");
else
printf("str1<str2\n");
//a==o同样的道理,这里就不作代码演示了
return 0;
}
输出结果为:str1<str2
4.测试字符长度函数strlen
一般形式:
strlen(字符数组名)
功能是测试字符串的实际长度(注意不含字符串结束符'\0','\0'不算作字符串的内容)并作为函数值返回
例如下面代码,这样便可以知道str中的字符串长度。
#include <stdio.h>
#include <string>
int main()
{
int k;
char str[] = "NICE";
k = strlen(str);
printf("%d", k); //k的结果为4
}
5.strupr和strwr函数
一般格式为:
strupr(字符数组名);
作用为将字符串转换为大写形式,不改变其他字符
一般格式为:
strlwr(字符数组名);
功能为将字符串转换为小写形式,不改变其他字符
例如
#include <stdio.h>
#include <string>
int main()
{
char str1[] = "nice!", str2[] = "GOOD!!";
_strupr(str1);//转化为大写
_strlwr(str2);//转化为小写
printf("%s\n", str1);
printf("%s\n", str2);
}
输出结果为