1,字符串输入与输出
- scanf()和printf()
直接通过C语言标准化输入输出函数实现,使用"%s"参数(单个字符用"%c")。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = {0};
scanf("%s",str);
printf("%s",str);
return 0;
}
说明:
输入字符串时,遇到回车或空格,输入结束,并且自动在串末尾加上结束标志'\0';
输出字符串时,遇到字符串结束标志'\0',输出结束。
- gets()和puts()
gets(str):从输入缓冲区中读取一个字符串存储到字符指针变量str所指向的内存空间;
puts(str):与printf("%s\n", str)作用相同,但是只能输出字符串,不能是数值或进行格式变换。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = {0};
gets(str);
puts(str);
return 0;
}
说明:
输入字符串时,遇到回车,输入结束。
gets()输入与scanf()输入不同的是,gets()允许接受空格字符。
gets(str)、pus(str)、scanf("%s", str)、printf("%s", str)可以混合使用。
2,字符串操作
- 计算字符串长度函数:strlen()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "China";
printf("%d",strlen(str));
return 0;
}
- 字符串赋值函数:strcpy()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[50];
char str2[10] = "Chinese!";
strcpy(str1,str2);
printf("%s\n",str1);
return 0;
}
- 字符串拼接函数:strcat()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[50] = "I am";
char str2[10] = " Chinese!";
strcat(str1,str2);
printf("%s\n",str1);
return 0;
}
- 字符串比较函数:strcmp()
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[10] = "aaaaa";
char str2[10] = "bbbb";
int value;
value = strcmp(str1,str2);
printf("%d",value);
return 0;
}
- 字符串查找函数:strstr()
char *strstr(const char *str1, const char *str2):字符串查找函数,用于查找一个字符串在另一个字符串中的位置。返回指向str1中第一次出现str2的指针;如果str2不是str1的一部分,则返回空指针。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str1[10] = "aabaa";
char str2[10] = "ba";
char *value;
value = strstr(str1,str2);
printf("%s",value);
return 0;
}
跳转: