我想知道如何計算一個字串中有多少個單詞。我strstr用來比較,它有效,但只有效一次
像這樣
char buff = "This is a real-life, or this is just fantasy";
char op = "is";
if (strstr(buff,op)){
count ;
}
printf("%d",count);
并且輸出是 1 但句子中有兩個“是”,請告訴我。
uj5u.com熱心網友回復:
在回圈中決議字串。
由于 OP 有“但句子中有兩個“是”,因此僅查找是不夠的,"is"因為在"This". 代碼需要決議字串以獲得“單詞”的概念。
區分大小寫也是一個問題。
char buff = "This is a real-life, or this is just fantasy";
char op = "is";
char *p = buff;
char *candidate;
while ((candidate = strstr(p, op)) {
// Add code to test if candidate is a stand-alone word
// Test if candidate is beginning of buff or prior character is a white-space.
// Test if candidate is end of buff or next character is a white-space/punctuation.
p = strlen(op); // advance
}
對我來說,我不會使用strstr(),而是尋找帶有isalpha().
// Concept code
size_t n = strlen(op);
while (*p) {
if (isalpha(*p)) { // Start of word
// some limited case insensitive compare
if (strnicmp(p, op, n) == 0 && !isalpha(p[n]) {
count ;
}
while (isalpha(*p)) p ; // Find end of word
} else {
p ;
}
}
uj5u.com熱心網友回復:
對于初學者,您必須至少像這樣撰寫宣告
char buff[] = "This is a real-life, or this is just fantasy";
const char *op = "is";
此外,如果您需要計算單詞,則必須檢查單詞是否由空格分隔。
您可以通過以下方式完成任務
#include <string.h>
#include <stdio.h>
#include <ctype.h>
//...
size_t n = strlen( op );
for ( const char *p = buff; ( p = strstr( p, op ) ) != NULL; p = n )
{
if ( p == buff || isblank( ( unsigned char )p[-1] ) )
{
if ( p[n] == '\0' || isblank( ( unsigned char )p[n] ) )
{
count ;
}
}
}
printf("%d",count);
這是一個演示程式。
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char buff[] = "This is a real-life, or this is just fantasy";
const char *op = "is";
size_t n = strlen( op );
size_t count = 0;
for ( const char *p = buff; ( p = strstr( p, op ) ) != NULL; p = n )
{
if ( p == buff || isblank( ( unsigned char )p[-1] ) )
{
if ( p[n] == '\0' || isblank( ( unsigned char )p[n] ) )
{
count ;
}
}
}
printf( "The word \"%s\" is encountered %zu time(s).\n", op, count );
return 0;
}
程式輸出是
The word "is" is encountered 2 time(s).
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/317084.html
上一篇:for回圈函式回傳函式外
下一篇:從for回圈輸出形成陣列
