常用的字符串处理函数
- 字符串的输入和输出
输入字符串
scanf("%s",s); //输入参数必须是字符型数组名
gets( ); //参数s是字符数组名,输入的字符串允许带空格
输出字符串
printf("%s",s); //输出参数 可以是字符数组名或字符串常量
puts( ); //参数s可以是字符数组名或字符串常量,成功执行后输出字符串,返回换行符
- 字符串的复制
char *strcpy(char *s1,char *s2);
//参数s1必须是字符型数组基地址,参数s2可以是字符数组名或字符串常量
简化:strcpy( s1,s2 );
int i;
char s1[80],s2[80],from[80] = "happy";
strcpy(str1,from); //把from中的字符串复制给str1;
strcpy(str2,"key"); //字符串"key"复制给str2;
- 字符串连接函数strcat(s1,s2)
char str1[80]="hello",str2[80],t[80]="world";
strcat(str1,t);
strcpy(str2,str1);
strcat(str2,"!");
- 字符串比较函数strcmp(s1,s2);
strcmp()参数s1和s2可以是字符数组名或字符串常量。
s1=s2,返回0。
s1>s2,返回正数。
s1<s2,返回负数。
- 字符串长度函数strlen(s1);
参数s1可以是字符数组名或字符串常量,strlen(s1)返回字符串s1的'\0'之前的字符个数。
#include<stdio.h>
int main()
{
char str[80];
//scanf("%s",str);
//printf("%s\n",str);
//printf("%s","hello");
gets(str);
puts(str);
puts("hello");
return 0;
}
//abcd\
//abcd\
//hello
#include<stdio.h>
#include<string.h>
int main()
{
char str1[80]="hello",str2[80],t[80]="world";
strcat(str1,t); //连接str1和t,结果放在str1中
strcpy(str2,str1); //str1中的字符串赋给str2
strcat(str2,"!"); //连接str2和字符串!
strcmp("happy","z");
strlen(str2);
printf("%s\n",str2);
printf("%d\n",strcmp("happy","z"));
printf("%d\n",strlen(str2));
return 0;
}
//helloworld!
//-1
//11