[英]Creating an array with char in C, taking two words from the user, changing the places of the words and giving them all to the screen at the end
[英]Count all signs, not white signs, all words and lines from char array in C
我得到一個任務。 我必須編寫一個包含幾個函數來分析文本的程序(計算單詞、符號、行,而不是白色符號等)。這是我的程序:
#include <stdio.h>
#include <stdlib.h>
int allSigns(char text[])
{
int i;
for (i = 0; text[i] != '\0'; ++i);
return i;
}
int notWhiteSigns(char text[])
{
int sum;
for (int i = 0; text[i] != '\0'; ++i)
{
if (text[i] != (' ' && '\n' && '\t'))
sum++;
}
return sum;
}
int words(char text[])
{
int i;
int sum = 0;
for (int i = 1; text[i] != '\0'; ++i)
{
if (text[i] == ' ' && text[i-1] && text[i] != ('\t' && '\n'))
sum++;
}
if (text[i-1] != ' ');
sum++;
return sum;
}
int lines(char text[])
{
int i;
int sum = 1;
for (int i = 0; text[i] != '\0'; ++i)
{
if (text[i] == '\n')
sum++;
}
return sum;
}
int main (int argc, char *argv[])
{
char sentence[] = "C is \n a \n programming \t language";
printf("Show array: %s \n", sentence);
printf("All signs: %i\n not white signs: %i\n words: %i\n lines: %i\n", allSigns(sentence), notWhiteSigns(sentence), words(sentence), lines(sentence));
return 0;
}
我的 output 是:
Show array: C is
a
programming language
All signs: 33
not white signs: 66
words: 8
lines: 3
我看到我犯了一些錯誤。 線沒問題(3)。 但我有8個字而不是5 個字。 計算所有單詞的 Function 沒問題(我將 \n 和 \t 算作一個)。 我不知道為什么我有66 個“非白色標志” (除 ''、'\n'、'\t' 之外的所有標志)我應該有 23 個
錯誤在這里:
if (text[i] != (' ' && '\n' && '\t'))
(' ' && '\n' && '\t')
中的每個字符都將表示為 ASCII 碼。 所以這個表達式的意思是(text[i] != (32 && 10 && 9))
。
試試這個:
if ((text[i] != ' ') && (text[i] != '\n') && (text[i] != '\t'))
您還應該在使用前初始化sum
變量。
您需要用零初始化 sum 並更改 if 語句:
int notWhiteSigns(char text[])
{
int sum = 0;
for (int i = 0; text[i] != '\0'; ++i)
{
if (text[i] != ' ' && text[i] != '\n' && text[i] != '\t')
sum++;
}
return sum;
}
在您的代碼中,您使用了兩個未初始化的變量:
function int notWhiteSigns(char text[])
中的第一個sum
需要為int sum=0
。
第二個:
int words(char text[])
{
int i;
int sum = 0;
for (int i = 1; text[i] != '\0'; ++i)
{
if ((text[i] != ' ') && (text[i] != '\n') && (text[i] != '\t'))
sum++;
}
if (text[i - 1] != ' ');
sum++;
return sum;
}
因為你已經在for-loop
中重新聲明了i
,所以你不會在循環之外擁有它的值,所以這里if (text[i - 1];= ' ');
您正在使用未初始化的i
從 for 循環中刪除int i
for (i = 1; text[i];= '\0'; ++i)
也如前所述,一次將Text i
與不同的值進行比較是錯誤的。
這應該是if ((text[i] != ' ') && (text[i] != '\n') && (text[i] != '\t'))
謝謝 function notwhiteSpace 工作正常。 我找到了計算單詞 function 的解決方案
int words(char text[])
{
int i;
int sum = 0;
for (int i = 1; text[i] != '\0'; ++i)
{
if (text[i] == ' ' && text[i-1] != ' ' && (text[i] != '\n') && (text[i] != '\t') && (text[i-1] != '\n') && (text[i-1] != '\t'))
sum++;
}
if (text[i-1] != ' ');
sum++;
return sum;
}
現在它可以正常工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.