newb初学者在这里。我试图理解如何在两个数组(单词和单词)之间循环,这样我就可以找出单词数组中每个元素出现多少次。 这是我的非工作代码,有人可以帮我看看我搞乱循环的地方吗?
谢谢!
#define MAXWORDS 100
#define ALLWORDS 1000
int main()
{
int c, state, nowords;
state = OUT;
int array[MAXWORDS] = {0};
char words[ALLWORDS] = {'0'};
for (int i = 0; i < MAXWORDS; ++i)
/* printf("%i", array[i]) */;
/* printf("\n"); */
/* Filling an array correctly!!! */
int count;
count = 0;
int countchars;
countchars = 0;
while((c = getchar())!= EOF)
{
words[countchars++] = c;
count++;
switch(c) {
case ' ':
case '\n':
case '\t':
if(state == IN)
{
state = OUT;
++nowords;
}
count = 0;
break;
default:
state = IN;
if(count > 0)
array[nowords] = count;
break;
}
}
words[countchars + 1] = '\0';
printf("number of chars in each word in the sentence: ");
for (int i = 0; array[i] != 0; i++)
printf("%i,", array[i]);
printf("\n");
printf("What was typed and stored into the words array: ");
for(int k = 0; words[k] != '\0'; k++)
printf("%c", words[k]);
printf("\n");
printf("Finding unique chars: ");
int a, b;
char uniques[ALLWORDS] = {'0'};
for(a = 0; a < countchars; a++)
{
for(b = 0; b < a; b++)
{
if(words[a] == words[b])
{
break;
}
}
if(a == b)
{
uniques[a] = words[a];
}
}
uniques[a + 1] = '\0';
for(int d = 0; d != ALLWORDS; d++)
printf("%c", uniques[d]);
printf("\n");
int counting = 0;
for(int j = 0; j < countchars; j++)
{
counting = 0;
for(int h = 0; h < a; h++)
{
if(words[h] == uniques[j])
++counting;
}
printf("\"%c\": %i ", uniques[j], counting);
printf("\n");
}
return 0;
}
我得到这样的输出有点奇怪:
./homework
a big fat herd of kittens
number of chars in each word in the sentence: 1,3,3,4,2,7,
What was typed and stored into the words array: a big fat herd of kittens
Finding unique chars: a bigftherdokns
"a": 2
" ": 5
"b": 1
"i": 2
"g": 1
"": 0
"f": 2
"": 0
"t": 3
"": 0
"h": 1
"e": 2
"r": 1
"d": 1
"": 0
"o": 1
"": 0
"": 0
"k": 1
"": 0
"": 0
"": 0
"": 0
"n": 1
"s": 1
"
": 1
答案 0 :(得分:0)
执行此操作的有效方法如下: 使用第三个数组:char count [5](必须与你的唯一数组相同) count [0]将保持字母'a'出现在“words”数组中的次数,count [1]将保持字母'b'出现在“words”数组中的次数,依此类推......
因此,在执行以下操作时,您只需要一个for循环: 检查单词[i]是否在唯一数组中(基本上你检查单词[i]&lt; ='e')。如果单词[i]确实是&lt; ='e'那么你将增加计数[words [i] - 'a']。
现在让我们看看“单词[i] - 'a'”实际上是如何运作的。 如果单词[i]是'a'那么你会有单词[i] - 'a'='a' - 'a'= 0(计数数组中的第一个位置) 如果单词[i]是'b'那么你会有单词[i] - 'a'='b' - 'a'= 1(计数数组中的第二个位置)。
你使用2 for for循环的低效方法。
此外,找到错误的好方法,特别是在像这样的小代码中,实际上是拿一张纸和一支笔,并尝试按照如何编写小输入的代码。另一种(更有效的方法)是逐步调试并实际查看每个变量的值。
希望我足够清楚。祝你好运:D