@FE40536
2019-07-03T21:02:31.000000Z
字数 1724
阅读 863
C
字符串
多个字符连接在一起,以\0结束的内容
char 数组名[] = "abcde";
char 数组名[] = {'a','b','c','d','\0'};
char *str = "abcde";char arr[3] = {'a','b'}; //也是字符串
char arr[3] = "abc" //不是字符串
字符串的输入输出占位符是%s
在scanf中如果输入空格或回车会自动结束,可以用gets(字符串)获取空格,puts(字符串)输出字符串
char str[10] = { 0 };
printf("请输入字符串\n");
scanf("%s", str);
printf(str);
gets(str); // 获取 输入 scanf
puts(str);
//有一句英语 计算有多少单词 每个单词以空格分隔
char str[100] = { 0 };
printf("input:");
gets(str);
int flag = 1;
int count = 0;
for (int i = 0; str[i] != '\0'; ++i)
{
if (str[i] == ' ')
{
flag = 1;
}
else if (flag == 1)
{
++count;
flag = 0;
}
}
printf("有%d个单词\n", count);
strcmp(str1, str2):字符串比较函数,比较ASCII码大小,strcmp(str1, str2)当str1>str2时返回1,等于时返回0,小于时返回-1
strlen(str1):字符串长度函数,不包括'\0'
strcat(str1, str2):字符串拼接函数,要预留有效位置
strcpy(str1, str2):字符串拷贝函数
strchr(str5, '@'):字符串查找函数,返回字符指针
strstr(str6, str5):判断str5是不是str6的子字符串
strset(str6, 's'):将str6所有字符设置成's'
char *str1 = "abc";
char str2[] = "bcd";
char str3[10] = "abcde";
char str4[] = "123";
char str5[] = "123@456"
//strcmp
int x = strcmp(str1, str2);
printf("%d\n", x);
//strlen
printf("strlen(str3) = %d\n", strlen(str3)); //strlen(str3) = 5
printf("sizeof(str2) = %d\n", sizeof(str3)); //sizeof(str2) = 10
//strcat
strcat(str3, str2);
printf("%s\n", str3);
//strcpy
strcpy(str3, str4);
printf("%s", str3);
//strchr
char *s1 = strchr(str5, '@');
printf("%c\n", *s1); //@
char *s2 = strchr(str5, '@');
printf("%s\n", s2); //@456
//strstr
int a = strstr(str6, str3);
printf("%s\n", a);
int b = strstr(str6, str5);
printf("%s\n", b);
输出
abcdef
(null)
//strset
strset(str6, 's');
printf("%s", str6);
输出
sssssssss
// 案例加密解密
char txt[128] = { 0 };
printf("请输入明文字符串:\n");
gets(txt);
int len = strlen(txt);
int i = 0;
for (; i < len; ++i)
{
txt[i] = txt[i] + i + 5;
}
txt[i] = '\0';
printf("加密字符串:%s\n", txt);
i = 0;
for (; i < len; ++i)
{
txt[i] = txt[i] - i - 5;
}
printf("解密后字符串:%s\n", txt);
输出
请输入明文字符串:
asdfasdfadsfads
加密字符串:fyknj}ornr倂rv?
解密后字符串:asdfasdfadsfads