[英]How to count numbers and characters of a string?
我必須做這個練習,我確實在盡力而為,但是我不知道該怎么解決。
它說我需要編寫一個程序來分析字符串。 它需要給出單詞和數字的數量。
請注意,數字也是一個單詞。 123是一個單詞和一個數字,但是例如4HIMATE不是一個數字,只有一個單詞。
我讓我到目前為止的代碼
int main()
{
int size= 256;
char s[256]= "Hi 123 Peter 8hi hi8";
char space[]= " ";
int wordCount= 0;
int numberCount= 0;
strcat(s, space);
strlwr(s);
for(int i= 0; s[i]!='\0'; i++)
{
if(s[i+1]== ' ' && s[i]>96 && s[i]<123)
{
wordCount++;
}
if(s[i+1]== ' ' && s[i]>47 && s[i]<58)
{
wordCount++;
}
}
for (int j=0; j<size; j++)
{
if(s[j+1]== ' ' && s[j]>47 && s[j]<58)
{
numberCount++;
}
}
printf("Words= %d\n", wordCount);
printf("Numbers= %d", numberCount);
return 0;
}
我的輸出必須是=
單詞= 5數字= 1
但錯誤在於數字,輸出為2。
我真的不知道該怎么解決,所以我需要一些幫助。
更正了一些錯誤(編輯):
for(int i= 0; s[i]!='\0'; i++)
{
if(s[i+1]== ' ' && s[i]>'a' && s[i]<'z')
{
wordCount++;
}
if(s[i+1]== ' ' && s[i]>'0' && s[i]<'9')
{
wordCount++;
}
}
for (int j=0; s[j]!='\0'; j++)
{
if(s[j+1]== ' ' && s[j]>'0' && s[j]<'9')
{
numberCount++;
}
}
您的邏輯有缺陷,因為您不會將最后一個“單詞”( hi8
)視為單詞。 同樣,如果數字在字符串的最后,您就不會計算在內。 這可以通過一些調試來發現。
一種可能的解決方案是使用狀態 。 一種狀態告訴您是否使用單詞,而另一種狀態則告訴您當前單詞是否為全數字。
使用狀態,遍歷字符串時,請檢查當前字符是否為字母數字字符 。 如果是,並且未設置is-a-word狀態,則設置該狀態。 更改狀態時,還請檢查當前字符是否為數字 ,然后設置為is-number狀態。 繼續循環,如果設置了is-a-word狀態,並且當前字符不是數字,則清除is-number狀態。 當到達某個空格時,請檢查您的狀態:如果設置了is-a-word,則清除它並增加單詞計數器; 如果設置了is-number狀態,則增加數字計數器並清除狀態。
用偽代碼可能是這樣的:
is-a-word-state = false
is-a-number-state = false
for each character in string
{
if (current-character is alphanumeric and is-a-word-state == false)
{
// Started a new word
is-a-word-state = true
if (current-character is digit)
{
// Could be a number
is-a-number-state = true
}
}
if (current-character is not digit)
{
// Current word (if any) is not a number
is-a-number-state = false
}
if (current-character is space)
{
if (is-a-word-state == true)
{
// End of the current word
word-counter++
if (is-a-number-state == true)
{
// Word is a number
number-counter++
}
}
is-a-word-state = false
is-a-number-state = false
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.