计算字符串中每个字母出现的次数 [英] Count the number of occurrences of each letter in string

查看:23
本文介绍了计算字符串中每个字母出现的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算字符串中每个字母(忽略大小写)在 c 中出现的次数?所以它会打印出 letter: # number of occurences,我有代码来计算一个字母的出现次数,但是如何计算字符串中每个字母的出现次数?

How can I count the number of occurrences in c of each letter (ignoring case) in the string? So that it would print out letter: # number of occurences, I have code to count the occurences of one letter, but how can I count the occurence of each letter in the string?

{
    char
    int count = 0;
    int i;

    //int length = strlen(string);

    for (i = 0; i < 20; i++)
    {
        if (string[i] == ch)
        {
            count++;
        }
    }

    return count;
}

输出:

a : 1
b : 0
c : 2
etc...

推荐答案

假设您有一个系统,其中 char 是 8 位,并且您尝试计算的所有字符都使用非编码-负数.在这种情况下,你可以写:

Let's assume you have a system where char is eight bit and all the characters you're trying to count are encoded using a non-negative number. In this case, you can write:

const char *str = "The quick brown fox jumped over the lazy dog.";

int counts[256] = { 0 };

int i;
size_t len = strlen(str);

for (i = 0; i < len; i++) {
    counts[(int)(str[i])]++;
}

for (i = 0; i < 256; i++) {
    if ( count[i] != 0) {
        printf("The %c. character has %d occurrences.
", i, counts[i]);
    }
}

请注意,这将计算字符串中的所有字符.如果你 100% 绝对肯定你的字符串里面只有字母(没有数字、没有空格、没有标点符号),那么 1. 要求不区分大小写"开始有意义,2. 你可以减少条目的数量到英文字母表中的字符数(即26),你可以这样写:

Note that this will count all the characters in the string. If you are 100% absolutely positively sure that your string will have only letters (no numbers, no whitespace, no punctuation) inside, then 1. asking for "case insensitiveness" starts to make sense, 2. you can reduce the number of entries to the number of characters in the English alphabet (namely 26) and you can write something like this:

#include <ctype.h>
#include <string.h>
#include <stdlib.h>

const char *str = "TheQuickBrownFoxJumpedOverTheLazyDog";

int counts[26] = { 0 };

int i;
size_t len = strlen(str);

for (i = 0; i < len; i++) {
    // Just in order that we don't shout ourselves in the foot
    char c = str[i];
    if (!isalpha(c)) continue;

    counts[(int)(tolower(c) - 'a')]++;
}

for (i = 0; i < 26; i++) {
    printf("'%c' has %2d occurrences.
", i + 'a', counts[i]);
}

这篇关于计算字符串中每个字母出现的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆