我已经坚持了一段时间了。我编写了我的程序来计算用户输入的字符串中的单词出现次数以及按字母顺序对单词进行排序。我的问题是我的程序只有在输入的单词之间有空格才能完美运行。例如,如果我输入“to to”,我的程序会将这两个单词计为两个不同的单词,因为逗号而不是将其计为“to”中的一个单词,如我所愿。这是数组const char delim[]
中所有分隔符的问题。如何在我的程序中解决此问题?我非常感谢任何帮助!我的代码如下:
编辑:我把鲍勃的建议用于使用strchr()并且它有效!我唯一的问题是我的程序现在输出分隔符的计数。我在考虑将words[i]
与words[j]
进行比较时可能会写一个if语句,看看它们是否具有相同的值。这是最好的方法吗?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
const char delim[] = ", . - !*()&^%$#@<> ? []{}\\ / \"";
#define SIZE 1000
int main(){
char string[SIZE], words[SIZE][SIZE], temp[SIZE];
int a = 0, i = 0, j = 0, k = 0, n = 0, count;
int c = 0, cnt[26] = { 0 };
int word = 0;
int x;
printf("Enter your input string:");
fgets(string, SIZE, stdin);
string[strlen(string) - 1] = '\0';
lower(string);
/*extracting each and every string and copying to a different place */
while (string[i] != '\0'){
if (strchr(", . - !*()&^%$#@<> ? []{}\\ / \"", string[i]) != NULL){
words[j][k] = '\0';
k = 0;
j++;
}else {
words[j][k++] = string[i];
}
i++;
}
words[j][k] = '\0';
n = j;
printf("Number of occurences of each word unsorted:\n");
i = 0;
/* find the frequency of each word and print the results */
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
for (a = j; a <= n; a++)
strcpy(words[a], words[a + 1]);
n--;
}
}//for
}
//word == strtok(string, delim);
/* count - indicates the frequecy of word[i] */
printf("%s\t%d\n", words[i], count);
i = i + 1;
}//while
printf("Alphabetical Order:\n");
/* sort the words in the given string */
for (i = 0; i < n; i++){
strcpy(temp, words[i]);
for (j = i + 1; j <= n; j++){
if (strcmp(words[i], words[j]) > 0){
strcpy(temp, words[j]);
strcpy(words[j], words[i]);
strcpy(words[i], temp);
}
} //inner for
} //outer for
i = 0;
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
}
}
}
printf("%s\n", words[i]);
i = i + count;
}
}
答案 0 :(得分:0)
在比较之前去除该范围的每个字。实际上你甚至不需要一个分界符列表,因为单词是&#39; alpha&#39;除此之外,它是一个分水岭。
答案 1 :(得分:0)
请尝试这个,它有效,它是你自己的代码的摘录,稍微修改一下,它会给你计数,然后你必须写下其余的,玩得开心。
#include <string.h>
#define YES 1
#define NO 0
int main( )
{
char string[1000];
int i = 0;
int j = 0;
int is_this_a_word = 0;
strcpy( string, " to or not ,tobe" );
while ( string[i++] != '\0' )
{
if ( strchr( ", . - !*()&^%$#@<> ? []{}\\ / \"", string[i] ) != NULL )
{
is_this_a_word = NO;
}
else
{
if ( ! is_this_a_word )
{
is_this_a_word = YES;
j++;
}
}
}
printf( "I counted %d words", j );
getchar( );
}