簡體   English   中英

在C中配對字符

[英]Pairing of characters in C

我正在編寫一個讀取文本文件的代碼,然后計算一對字母出現的實例數。 例如,包含“aabbaa”的文本文件

出現的次數是aa = 2,ab = 1,ba = 1

我以為我可以使用像這樣的2D數組:

char charPair[25][25] =   {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w ','x','y','z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

但這只會返回一個字母。

任何幫助,將不勝感激!

重要提示:如果您聲明了char -array,那么如果組合發生超過255次,則條目將溢出,因此我將其更改為long

另外請記住,您的2D數組應該包含您正在使用的字母表中每個字母的索引。 我假設它是26個字母(例如只有ascii小寫):

long charPair[26][26];
memset(charPair, 0, 26*26*sizeof(long));
char* reader = yourInput;
char current = *reader-'a';
++reader;
char next = *reader-'a';
while(next!=0) { // assumes \0-terminated
    charPair[current][next] += 1;
    current = next;
    next = *reader-'a';
    ++reader;
}

-'a'是這樣的,字母a將有行/列0,z將有26。

編輯:關於如何最好地讀取輸入的評論:上面的代碼假定整個輸入被放入一個字符串(\\ 0終止)

FILE* f = fopen(filename, "rb"); // (todo: add your error handling if 0 returned)
fseek(f, 0, SEEK_END);
int len = ftell(f);
fseek(f, 0, SEEK_SET);
char* yourInput = malloc(len+1); // (todo: add your error handling if 0 returned)
fread(yourInput, 1, len, f); // (todo: add your error handling if <len returned)
yourInput[len] = '\0';
fclose(f);

在c ++'ish C中,請根據需要進行轉換,變量聲明,注釋等...

...

char tCharPairCount[26][26]; // Lower-Case strings only
memset(tCharPairCount,0,26*26);

char tPrevChar = tempString[0];
for(int i=1; i<tempString.length(); ++i ) 
{
   char tCurrentChar = tempString[i];
   ++tCharPairCount[tPrevChar-'a'][tCurrentChar-'a'];
   tPrevChar = tCurrentChar;
}

...

//迭代結果

for(i:0->25)
for(j:0->25)
 printf("%i",tCharPairCount[i][j]);  // 0,0 => aa ; 1,0 => ba

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM