我一直在此停留了一段時間。我編寫了我的程序來計算用戶輸入的字符串中的單詞出現情況,並按字母順序對單詞進行排序。我的問題是我的程序只有在輸入的單詞之間有空格時才能正常運行。例如,如果我輸入「to to」,我的程序會將這兩個單詞計爲兩個不同的單詞,而不是按照我的意願將它計爲「to」中的一個單詞。這是對於陣列const char delim[]
中的所有分隔符的問題。我如何在我的程序中解決這個問題?我非常感謝任何幫助!我的代碼如下:在字符串C編程中對字出現進行排序
編輯:我採取了鮑勃的建議,使用strchr(),它的工作!我唯一的問題是我的程序現在輸出分隔符的計數。我想在比較words[i]
和words[j]
時可能會寫if語句,看他們是否具有相同的值。這是最好的方法嗎?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
const char delim[] = ", . - !*()&^%$#@<> ? []{}\\/\"";
#define SIZE 1000
int main(){
char string[SIZE], words[SIZE][SIZE], temp[SIZE];
int a = 0, i = 0, j = 0, k = 0, n = 0, count;
int c = 0, cnt[26] = { 0 };
int word = 0;
int x;
printf("Enter your input string:");
fgets(string, SIZE, stdin);
string[strlen(string) - 1] = '\0';
lower(string);
/*extracting each and every string and copying to a different place */
while (string[i] != '\0'){
if (strchr(", . - !*()&^%$#@<> ? []{}\\/\"", string[i]) != NULL){
words[j][k] = '\0';
k = 0;
j++;
}else {
words[j][k++] = string[i];
}
i++;
}
words[j][k] = '\0';
n = j;
printf("Number of occurences of each word unsorted:\n");
i = 0;
/* find the frequency of each word and print the results */
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
for (a = j; a <= n; a++)
strcpy(words[a], words[a + 1]);
n--;
}
}//for
}
//word == strtok(string, delim);
/* count - indicates the frequecy of word[i] */
printf("%s\t%d\n", words[i], count);
i = i + 1;
}//while
printf("Alphabetical Order:\n");
/* sort the words in the given string */
for (i = 0; i < n; i++){
strcpy(temp, words[i]);
for (j = i + 1; j <= n; j++){
if (strcmp(words[i], words[j]) > 0){
strcpy(temp, words[j]);
strcpy(words[j], words[i]);
strcpy(words[i], temp);
}
} //inner for
} //outer for
i = 0;
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
}
}
}
printf("%s\n", words[i]);
i = i + count;
}
}
您是否聽說過函數/方法? –
@MitchWheat是的,我有爲什麼?另外,聽說過strtok,但我不知道如何在這裏使用它。 – Omar
那麼我強烈建議使用它們... –