下面是您的代碼的工作版本和測試程序。
#include <stdbool.h>
#include <stdio.h>
static int wc(const char *str)
{
int count = 0;
bool inword = false;
char c;
while ((c = *str++) != '\0')
{
if (c == ' ')
inword = false;
else
{
if (inword == false)
count++;
inword = true;
}
}
return count;
}
static void Number(const char *tests[], int num_tests)
{
for (int i = 0; i < num_tests; i++)
printf("%d: [%s]\n", wc(tests[i]), tests[i]);
}
int main(void)
{
const char *tests[] =
{
"",
" ",
" ",
"a",
"a b",
" a b ",
" ab cd ",
"The quick brown fox jumps over the lazy dog.",
" The quick brown fox jumps over the lazy dog. ",
};
enum { NUM_TESTS = sizeof(tests)/sizeof(tests[0]) };
Number(tests, NUM_TESTS);
return 0;
}
請注意,您函數完成兩項工作 - 並且應該只做一,委託對方一個單獨的函數。它既計算單個字符串中的單詞並打印相關信息。我將計數單詞委託給單獨的函數wc()
,這極大地簡化了中的代碼 - 幾乎不需要該函數。還請注意,我的版本被告知它正在處理的數組的條目數量,而不是依賴像4
這樣的幻數。請注意,我的代碼輸出允許您檢查它的準確性。只需打印輸出號碼不會讓您輕鬆檢查準確性;您必須查看代碼才能瞭解數字的含義。請注意,您的函數被定義爲返回int
,但實際上並沒有這樣做。這個版本被定義爲不返回任何東西,而不是。
從代碼的輸出是:
0: []
0: [ ]
0: [ ]
1: [a]
2: [a b]
2: [ a b ]
2: [ ab cd ]
9: [The quick brown fox jumps over the lazy dog.]
9: [ The quick brown fox jumps over the lazy dog. ]
很顯然,你可以使用isblank()
或isspace()
宏(功能)從<ctype.h>
細化空間測試,如果你願意,也可以定義字和不可─之間的邊界用其他方式說話。儘管如此,基本的概念是可靠的,可以跨越空白和文字的相當不正確的序列。
如果你真的想要一個二維數組的字符,編寫代碼來處理這個問題並不難,儘管'懶狗'字符串將不得不簡化爲適合char data[][20]
。基本思路保持不變 - wc()
函數不會改變。
#include <stdbool.h>
#include <stdio.h>
static int wc(const char *str)
{
int count = 0;
bool inword = false;
char c;
while ((c = *str++) != '\0')
{
if (c == ' ')
inword = false;
else
{
if (inword == false)
count++;
inword = true;
}
}
return count;
}
static void Number(const char tests[][20], int num_tests)
{
for (int i = 0; i < num_tests; i++)
printf("%d: [%s]\n", wc(tests[i]), tests[i]);
}
int main(void)
{
const char tests[][20] =
{
"",
" ",
" ",
"a",
"a b",
" a b ",
" ab cd ",
"The quick brown fox",
" jumps over ",
" the lazy dog ",
};
enum { NUM_TESTS = sizeof(tests)/sizeof(tests[0]) };
Number(tests, NUM_TESTS);
return 0;
}
輸出:
0: []
0: [ ]
0: [ ]
1: [a]
2: [a b]
2: [ a b ]
2: [ ab cd ]
4: [The quick brown fox]
2: [ jumps over ]
3: [ the lazy dog ]
測試像" ab cd "
例子(帶雙空格在開始,中間和結尾)往往是非常好的推邊緣情況 - 在不僅僅是字計數多個上下文。例如,許多shell腳本不會正確處理像那個字符串這樣的參數。
如果字符串是 「空」,即,僅包括' 「\ 0」''然後\ 0'將被計數,但否則'do .. while()'循環條件將'\ 0'排除在考慮之外。我建議使用'while(){...}'循環。想一想「何時出現'\ 0'字符」。它不是* C字符串中的字符*,而是它的結束標記。 –
當它到達\ 0字符時,循環停止,那麼爲什麼你認爲它會被計算? – immibis
while循環不起作用。如果我沒有在一行中放入任何二維數組,那麼這一段時間根本不會被執行......儘管在我寫論壇之前,我仍嘗試過。 –