字符数组 和 字符串区别:
字符数组:
char str[5] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’};
字符串:
char str[6] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};
char str[6] = “hello”;
printf("%s"); 使用printf打印字符串的时候,必须碰到 \0 结束。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main()
{
char str[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
char str2[] = "world"; // == {'w', 'o', 'r', 'l', 'd', '\0'}
printf("%s\n", str2);
}
练习:键盘输入字符串,存至str[]中,统计每个字母出现的次数
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int main()
{
char str[10] = { 0 }; // helloworld --> 26个英文字母 a-z a:97 d:100
// scanf("%s", str);
for (int i = 0; i < 10; i++)
{
scanf("%c", &str[i]);
}
int count[26] = { 0 }; // 代表26个英文字母出现的次数。
for (int i = 0; i < 11; i++)
{
int index = str[i] - 'a'; // 用户输入的字符在 count数组中的下标值。
count[index]++;
}
for (int i = 0; i < 26; i++)
{
if (count[i] != 0)
{
printf("%c字符在字符串中出现 %d 次\n", i + 'a', count[i]);
}
}
}