2013-05-09 34 views
2

我試圖檢查,看看我給一個字符數組 - 這樣有沒有什麼辦法來檢查C中的字符串中是否存在任何或全部字符?

char array_values[] = { 'A','B','C','D','a','b','c','d' }; 

,然後運行一種在多串字符匹配的EG-

.... 
str1 = 'AACDBACBAabcAcddaAABD' 
str2 = 'aacbdAABDCAaDDCBCAabc' 
.... 

,然後再返回字符串中存在的每個字符的計數。

我知道這很容易在python,R,perl中完成,但我想用C來解決這個問題。 也許像正則表達式那樣?有任何想法嗎?

+0

您使用ANSI C嗎?因爲如果你是正規表達式不是ANSI C的一部分,你必須使用循環機制。 – Marco 2013-05-09 13:04:46

+0

你想做什麼?對於每個字符串'strX',計算'array_values'中每個字符出現的頻率? – 2013-05-09 13:05:40

+0

'strpbrk'是第一部分的選項。 – 2013-05-09 13:05:43

回答

4

做C語言中的最簡單方法是在array_values不論其存在的數每一個字符,然後用array_values項目爲指標進入計數的陣列來獲得滿意的結果:

int count[256]; 
for (int i = 0 ; i != 256 ; count[i++] = 0); 
// The example works with a single string. For multiple strings, 
// iterate over the strings from your source in a loop, assigning str 
// and incrementing the counts for each of your strings. 
char *str = "AACDBACBAabcAcddaAABD"; 
for (char *p = str ; *p ; count[(unsigned char)*p++]++); 
char array_values[] = { 'A','B','C','D','a','b','c','d' }; 
for (int i = 0 ; i != 8 ; i++) { 
    printf("Found '%c' %d times", array_values[i], count[(unsigned char)array_values[i]]); 
} 

這裏一個demo on ideone

+0

注意:在大多數實現中,字符**默認**簽名**。 – wildplasser 2013-05-09 13:19:33

+0

@wildplasser你說得對,添加'unsigned'是個好主意。謝謝! – dasblinkenlight 2013-05-09 13:27:44

+0

你現在投它的方式會繞回到UINT_MAX-某事,恕我直言。 (肯定會崩潰) – wildplasser 2013-05-09 13:30:12

相關問題