4

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

{
    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...
4

15 回答 15

8

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

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.\n", i, counts[i]);
    }
}

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

#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.\n", i + 'a', counts[i]);
}
于 2012-11-03T21:01:53.963 回答
1

像这样:

int counts[26];
memset(counts, 0, sizeof(counts));
char *p = string;
while (*p) {
    counts[tolower(*p++) - 'a']++;
}

此代码假定字符串以空值结尾,并且仅包含a通过zA通过Z(包括)的字符。

要了解它是如何工作的,请记住转换后tolower每个字母在a和之间都有一个代码z,并且这些代码是连续的。结果,tolower(*p) - 'a'计算结果为从025(含)的数字,表示字母在字母表中的序号。

此代码结合++*p缩短了程序。

于 2012-11-03T21:00:16.630 回答
1

一种简单的可能性是创建一个包含 26 个整数的数组,每个整数都是一个字母 az 的计数:

int alphacount[26] = {0}; //[0] = 'a', [1] = 'b', etc

然后遍历字符串并增加每个字母的计数:

for(int i = 0; i<strlen(mystring); i++)      //for the whole length of the string
    if(isalpha(mystring[i]))
        alphacount[tolower(mystring[i])-'a']++;  //make the letter lower case (if it's not)
                                                 //then use it as an offset into the array
                                                 //and increment

这是一个适用于 AZ、az 的简单想法。如果您想用大写字母分隔,您只需将计数改为 52 并减去正确的 ASCII 偏移量

于 2012-11-03T21:08:34.473 回答
1

接受回答后

符合这些规范的方法:(IMO,其他答案并不完全满足)

  1. char当范围很广时,它是实用/高效的。示例:CHAR_BITis 16or 32,所以没有使用bool Used[1 << CHAR_BIT];

  2. 适用于长的字符串(使用size_t而不是int)。

  3. 不依赖 ASCII。( Use Upper[])

  4. char当 a < 0 时定义的行为。is...()函数定义为EOFunsigned char

    static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    static const char Lower[] = "abcdefghijklmnopqrstuvwxyz";
    
    void LetterOccurrences(size_t *Count, const char *s) {
      memset(Count, 0, sizeof *Count * 26);
      while (*s) {
        unsigned char ch = *s;
        if (isalpha(ch)) {
          const char *caseset = Upper;
          char *p = strchr(caseset, ch);
          if (p == NULL) {
            caseset = Lower;
            p = strchr(caseset, ch);
          }
          if (p != NULL) {
            Count[p - caseset]++;
          }
        }
      }
    }
    
    // sample usage
    char *s = foo();
    size_t Count[26];
    LetterOccurrences(Count, s);
    for (int i=0; i<26; i++)
      printf("%c : %zu\n", Upper[i], Count[i]);
    }
    
于 2014-08-23T19:14:30.710 回答
1
#include <stdio.h>
#include <string.h>
void main()
{
    printf("PLEASE ENTER A STRING\n");
    printf("GIVE ONLY ONE SPACE BETWEEN WORDS\n");
    printf("PRESS ENETR WHEN FINISHED\n");

    char str[100];
    int arr[26]={0};
    char ch;
    int i;

    gets(str);
    int n=strlen(str);

    for(i=0;i<n;i++)
    {
        ch=tolower(str[i]);
        if(ch>=97 && ch<=122)   
        {
            arr[ch-97]++;
        }
    }
    for(i=97;i<=122;i++)
        printf("%c OCCURS %d NUMBER OF TIMES\n",i,arr[i-97]);   
    return 0;
}
于 2016-12-21T07:49:36.967 回答
0

您可以使用以下代码。

main()
{
    int i = 0,j=0,count[26]={0};
    char ch = 97;
    char string[100]="Hello how are you buddy ?";
    for (i = 0; i < 100; i++)
    {
        for(j=0;j<26;j++)
            {
            if (tolower(string[i]) == (ch+j))
                {
                    count[j]++;
                }
        }
    }
    for(j=0;j<26;j++)
        {

            printf("\n%c -> %d",97+j,count[j]);

    }

}

希望这可以帮助。

于 2012-11-03T21:07:42.770 回答
0
#include<stdio.h>
#include<string.h>

#define filename "somefile.txt"

int main()
{
    FILE *fp;
    int count[26] = {0}, i, c;  
    char ch;
    char alpha[27] = "abcdefghijklmnopqrstuwxyz";
    fp = fopen(filename,"r");
    if(fp == NULL)
        printf("file not found\n");
    while( (ch = fgetc(fp)) != EOF) {
        c = 0;
        while(alpha[c] != '\0') {

            if(alpha[c] == ch) {
                count[c]++; 
            }
            c++;
        }
    }
    for(i = 0; i<26;i++) {
        printf("character %c occured %d number of times\n",alpha[i], count[i]);
    }
    return 0;
}
于 2013-10-24T12:10:47.060 回答
0
for (int i=0;i<word.length();i++){
         int counter=0;
         for (int j=0;j<word.length();j++){
             if(word.charAt(i)==word.charAt(j))
             counter++;
             }// inner for
             JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
         }// outer for
于 2013-12-15T13:37:24.713 回答
0

这是带有用户定义函数的 C 代码:

/* C Program to count the frequency of characters in a given String */

#include <stdio.h>
#include <string.h>

const char letters[] = "abcdefghijklmnopqrstuvwxzy";

void find_frequency(const char *string, int *count);

int main() {
    char string[100];
    int count[26] = { 0 };
    int i;

    printf("Input a string: ");
    if (!fgets(string, sizeof string, stdin))
        return 1;

    find_frequency(string, count);

    printf("Character Counts\n");

    for (i = 0; i < 26; i++) {
        printf("%c\t%d\n", letters[i], count[i]);
    }
    return 0;
}

void find_frequency(const char *string, int *count) {
    int i;
    for (i = 0; string[i] != '\0'; i++) {
        p = strchr(letters, string[i]);
        if (p != NULL) {
            count[p - letters]++;
        }
    }
}
于 2015-06-23T05:34:51.407 回答
0
#include<stdio.h>

void frequency_counter(char* str)
{
    int count[256] = {0};  //partial initialization
    int i;

    for(i=0;str[i];i++)
        count[str[i]]++;

    for(i=0;str[i];i++) {
        if(count[str[i]]) {
            printf("%c %d \n",str[i],count[str[i]]);
            count[str[i]]=0;
        }
    }
}

void main()
{
    char str[] = "The quick brown fox jumped over the lazy dog.";
    frequency_counter(str);
}
于 2018-10-13T18:27:09.577 回答
0

已经检查了许多答案都是静态数组,如果假设我在字符串中有特殊字符并想要一个具有动态概念的解决方案怎么办。可能有许多其他可能的解决方案,它就是其中之一。

这是链接列表的解决方案。

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

struct Node { 
    char data; 
    int counter;
    struct Node* next; 
};

void printLinkList(struct Node* head)
{
    while (head != NULL) { 
        printf("\n%c occur %d", head->data, head->counter);
        head = head->next;
    }
}

int main(void) {
    char *str = "!count all the occurances of character in string!";
    int i = 0;
    char tempChar;
    struct Node* head = NULL; 
    struct Node* node = NULL; 
    struct Node* first = NULL; 

    for(i = 0; i < strlen(str); i++)
    {
        tempChar = str[i];

        head = first;

        if(head == NULL)
        {
            node = (struct Node*)malloc(sizeof(struct Node));
            node->data = tempChar;
            node->counter = 1;
            node->next = NULL;

            if(first == NULL)
            {
                first = node;
            }
        }
        else
        {
            while (head->next != NULL) { 
                if(head->data == tempChar)
                {
                    head->counter = head->counter + 1;
                    break;
                }
                head = head->next;
            }

            if(head->next == NULL)
            {
                if(head->data == tempChar)
                {
                    head->counter = head->counter + 1;
                }
                else
                {
                    node = (struct Node*)malloc(sizeof(struct Node));
                    node->data = tempChar;
                    node->counter = 1;
                    node->next = NULL;
                    head->next = node;
                }
            }
        }
    }

    printLinkList(first);


    return 0;
}
于 2019-09-20T05:27:45.543 回答
-1
int charset[256] = {0};
int charcount[256] = {0};

for (i = 0; i < 20; i++)
{
    for(int c = 0; c < 256; c++)
    {
        if(string[i] == charset[c])
        {
           charcount[c]++;
        }
    }
}

charcount 将存储字符串中任何字符的出现。

于 2012-11-03T21:00:29.333 回答
-1

//这是JavaScript代码。

function countWordOccurences()
{
    // You can use array of words or a sentence split with space.
    var sentence = "The quick brown fox jumped over the lazy dog.";
    //var sentenceArray = ['asdf', 'asdf', 'sfd', 'qwr', 'qwr'];
    var sentenceArray = sentence.split(' ', 1000); 
    var output;
    var temp;
    for(var i = 0; i < sentenceArray.length; i++) {
        var k = 1;
        for(var j = i + 1; j < sentenceArray.length; j++) {
            if(sentenceArray[i] == sentenceArray[j])
                    k = k + 1;
        }
        if(k > 1) {
            i = i + 1;
            output = output + ',' + k + ',' + k;
        }
        else
            output = output + ',' + k;
    }
    alert(sentenceArray + '\n' + output.slice(10).split(',', 500));
}

You can see it live --> http://jsfiddle.net/rammipr/ahq8nxpf/
于 2015-10-01T11:10:49.000 回答
-1

//c 代码用于计算字符串中每个字符的出现次数。

void main()
   {
   int i,j; int c[26],count=0; char a[]="shahid";
   clrscr();
   for(i=0;i<26;i++)
    {
        count=0;
          for(j=0;j<strlen(a);j++)
                {
                 if(a[j]==97+i)
                    {
                     count++;
                         }
                           }
                  c[i]=count;
               }
              for(i=0;i<26;i++)
               {
              j=97+i;
          if(c[i]!=0) {  printf("%c of %d times\n",j,c[i]);
                 }
              }
           getch();
           }
于 2016-02-12T17:44:21.540 回答
-1
protected void btnSave_Click(object sender, EventArgs e)
    {           
        var FullName = "stackoverflow"

        char[] charArray = FullName.ToLower().ToCharArray();
        Dictionary<char, int> counter = new Dictionary<char, int>();
        int tempVar = 0;
        foreach (var item in charArray)
        {
            if (counter.TryGetValue(item, out tempVar))
            {
                counter[item] += 1;
            }
            else
            {
                counter.Add(item, 1);
            }
        }
        //var numberofchars = "";
        foreach (KeyValuePair<char, int> item in counter)
        {
            if (counter.Count > 0)
            {
                //Label1.Text=split(item.
            }
            Response.Write(item.Value + " " + item.Key + "<br />");
            // Label1.Text=item.Value + " " + item.Key + "<br />";
            spnDisplay.InnerText= item.Value + " " + item.Key + "<br />";
        }

    }
于 2017-01-25T04:15:26.080 回答