C语言中的数组(5)---字符数组与字符串(附案例:键盘输入字符串,存至str[]中,统计每个字母出现的次数)

本文对比了字符数组和字符串的使用方法,包括定义、内存管理与printf输出的区别,并提供了一个统计字符串中字母出现次数的实例。通过实际操作演示了如何处理用户输入并计数字母频率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符数组 和 字符串区别:

字符数组:

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]);
		}
	}
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值