2012-11-03 549 views
2

如何計算字符串中每個字母的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... 

回答

8

讓我們假設你有一個系統,其中char是8位,你試圖計數的所有字符都是用非負數編碼的。在這種情況下,您可以編寫:

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++) { 
    printf("The %d. 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]); 
} 
+0

此代碼給我這個: 0.字符有0次出現。 1.字符出現0次。 ..... – enginefree

+0

@ user1786283你列出的是**短跑**('-')。我不相信你明白了。 – 2012-11-03 21:23:48

+0

@ user1786283 Aaaaaaand ...那有什麼不對?這意味着字符「0x00」沒有出現。等等。您知道,如果您使用的是基於GUI的現代操作系統,終端窗口右側會出現一個滾動條。另外,你是否努力嘗試第二個代碼被剪切? – 2012-11-03 21:25:52

2

像這樣:

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

此代碼假定該字符串是空終止,並且它僅包含字符a通過zA通過Z , 包括的。

要理解這是如何工作的,請記住,轉換後tolower每個字母的代碼介於az之間,並且代碼是連續的。結果,tolower(*p) - 'a'的計算結果爲從025(含),代表該字母在字母表中的順序編號。

此代碼結合++*p縮短程序。

+0

Woops,其實我們既不設法充分注意OP ;-) 「忽略大小寫」 是他的意思。 – 2012-11-03 21:03:42

+0

@ H2CO3你是對的,謝謝!我添加了「tolower」,並擴展了假設。非常感謝你! – dasblinkenlight

+0

不客氣。 (我會延長我的答案。) – 2012-11-03 21:07:39

0
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將存儲字符串中任何字符的發生。

1

您可以使用下面的代碼。

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

    } 

} 

希望這會有所幫助。

+1

對於字符串'快速棕色狐狸跳過懶狗。'它給我,'一個 - > 0 乙 - > 1 Ç - > 1 d - > 0 ë - > 1級 的F - > 1 克 - > 0 ħ - > 1 我 - > 1 的J - > 0 的k - > 1 升 - > 0 米 - > 0 N - > 1 -O - > 2 p - > 0 q - > 1個 的R - > 1 秒 - > 0 噸 - > 1 :U - > 1 N - > 0 瓦特 - > 1 X - > 1 ý - > 0 ž - > 0',但每封信都應該是1。 – enginefree

+0

在信中跳'' – enginefree

+0

@ user1786283你確定你沒有寫「跳」嗎? – 2012-11-03 21:16:30

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偏移

1
#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; 
} 
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 
0

接受符合這些規範的方法回答

雖然之後。 (IMO,其他答案不符合所有)

  1. 實用/有效時char範圍。 IWO:CHAR_BIT1632,所以沒有bool Used[1 << CHAR_BIT];

  2. Works爲非常長字符串(使用size_t而非int)。

  3. 不依賴於ASCII。 (Use Upper[]

  4. 定義的行爲當charEOF定義和unsigned char

    static const char Upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 
    static const char Lower[] = "abcdefghijklmnopqrstuvwxyz"; 
    
    void LetterOccurances(size_t *Count, const char *s) { 
        memset(Count, 0, 26*sizeof Count); 
        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]; 
    LetterOccurances(Count, s); 
    for (int i=0; i<26; i++) 
        printf("%c : %zu\n", Upper[i], Count[i]); 
    } 
    
0
這裏

是C代碼與用戶定義的函數:

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

#include <stdio.h> 

void find_frequency(char string[], int count[]); 

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

    printf("Input a string\n"); 
    gets(string); 

    find_frequency(string, count); 

    printf("Character Count\n"); 

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

void find_frequency(char string[], int count[]) 
{ 
    int i; 

    for(i = 0; string[i] != '\0'; i++) 
    { 
     if (string[i] >= 'a' && string[i] <= 'z') 
     { 
      count[string[i]-'a']++; 
     } 
    } 
} 
0

//這是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/ 
+0

這不是一個問題的答案... OP要求一個C程序,而不是JavaScript。 –

0

// 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(); 
      } 
2
#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; 
} 
+0

這是一個字符即將出現在特定字符串中的時間。 –

0
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 />"; 
     } 

    } 
+1

添加一些解釋並回答這個答案如何幫助OP解決當前問題 –

相關問題