计算字符串中数字出现的频率

标签 c string loops frequency digits

我需要实现一个可以计算字符串中数字位数的函数。所以对于数字,但也对于像:aD23b 这样的东西。如果我能让它工作......它应该看起来像:
输入:0912302
输出:
0: 2
1:1
2:2
3:1
4: 0
5: 0
6: 0
7: 0
8:0
9:1

不幸的是,此时我无法编写任何有用的代码...我的基本想法是:使用循环检查输入中的每个字符,如果它是数字,则将其存储在第二个数组中(比如说频率)。我遇到的问题是我需要以某种方式将每个字符转换为整数或以某种方式能够计算出 通常每个数字都会出现......我希望这可能会起作用,但它根本不起作用:

我忘了说我是编程的初学者,所以如果你能给我提示和解释,我将不胜感激。

void calc_occurrences(int s[], int occurrences[])
{
int i = 0;
    int j;
    int count = 0;
    while (s[i] != '\0') {
        if (isdigit(s[i])) {
            for (j = 0; occurrences[j] != '\0'; j++) {
                occurrences[j] = s[i];
            }
        }
        i++;
        for (j = i + 1; s[j] != '\0'; j++) {
            if (isdigit(s[i]) == isdigit(s[j])) {
                count++;
                occurrences[j] = 0;
            }
        }

        if(occurrences[i] != 0) {
            occurrences[i] = count;
        }
    }
}

最佳答案

制作一个数组来计算每个相关字符的出现频率。

像这样:

#include <stdio.h>

void count_freq(char* str, int freq[10])
{
    int i = 0;
    while(str[i])  // Loop to end of string
    {
        if (str[i] >= '0' && str[i] <= '9') // Check that the character is in range
        {
            ++freq[str[i]-'0'];  // notice the -'0' to get in range 0..9
        }
        ++i;
    }
}

int main(void) {
    int freq[10] = {0};             // Array to count occurence
    char str[] = "0034364hh324h34"; // Input string

    count_freq(str, freq);          // Calculate frequency

    for (int i=0; i < 10; ++i)      // Print result
    {
        printf("%d: %d\n", i, freq[i]);
    }
    return 0;
}

输出:

0: 2
1: 0
2: 1
3: 4
4: 4
5: 0
6: 1
7: 0
8: 0
9: 0

关于计算字符串中数字出现的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53573844/

相关文章:

c - 服务器未准备好时如何使连接失败?

c# - 使用双 Foreach 循环输出数据时结果相同

c - "void*"指针声明和 "void"关键字在内存分配过程中是如何关联的?

c - 优化C编译: removed unreferenced parts on-the-fly

c++ - 段错误常见原因的最终列表

algorithm - 反转字符串中单词的顺序

c++ - c++ 中字节的十六进制值到字符串(相当于 od -x 在 linux 中)?

java - java如何隐式创建对象?就像 String 类的情况一样

Perl:读取文件时跳过第 N 行

r - 识别 R 中的模式,相应地计算和分配值