[英]Counting words in a string in C
我写了一段代码来计算一个字符串包含多少个单词。
我已经尝试了多个输入,并且大多数输入都是正确的,但有些情况表明我的程序存在基本的逻辑缺陷。 例如,如果我在一个空字符串中设置,output 将错误地为 1,如果我在字符串的末尾添加空格,由于某种原因,我不知道 output 将是 1+其中的实际单词数字符串,正如我的代码显然表明的那样,我想去掉所有的空格/制表符。
我的程序基本上是在一个字符串中这样做的,但不幸的是没有在它的末尾。 我很清楚我的 function 有问题,但我不知道是什么问题。 而且我知道借助外部库可能更容易实现它,但我被要求用纯基本代码来实现它。
这是我到目前为止所拥有的:
int get_number_of_words(char input_string[])
{
int i, j, counter = 0;
for (i = 0; i < STRING_SIZE; i++)
{
if (input_string[i] != ' ')
{
counter++;
j = i;
while ((input_string[j] != ' '))
j++;
i = j;
}
}
return counter;
}
我会给你一些输入和 output 字符串的例子:
"Hello\t\t\t"
- 1 个单词(标签被忽略)"Hello"
- 1 个字""
- 0 个单词"\t\tThis is a basic example\t\t\t"
- 5 个单词(忽略制表符)"This is a basic example "
- 也是 5 个单词(忽略最后的空格)稍后,我将不得不考虑不同的标点符号(包含在单词中),但与此同时,我只想掌握程序的核心。
如果您只是在寻找一种可行的算法,那么逻辑如下:
那应该是你的答案。 我希望你能把指令转换成程序。
这是修改后的代码。 请参考评论以获得更好的理解。 我还假设 STRING_SIZE 将大于输入字符串的长度。
int get_number_of_words(char input_string[])
{
int i, j, counter = 0;
for (i = 0; i < STRING_SIZE; i++)
{
// This makes sure that when the 'i' in input_string is reached to end,
// you must not check further. It is basically last char of string.
if(input_string[i]=='\0')break;
// only enter this if condition if encounter a char a-z or A-Z
if((input_string[i]>='A'&&input_string[i]<='Z')||(input_string[i]>='a'&&input_string[i]<='z'))
{
counter++;
j = i;
// if there is no ' ' then this loop will run forever.
// thus added a constraint.
// iterate this loop till you read char from a-z or A-Z
while (j<STRING_SIZE && ((input_string[j]>='A'&&input_string[j]<='Z')||(input_string[j]>='a'&&input_string[j]<='z')))
j++;
i = j;
}
}
return counter;
}
使用如下循环:
for (i = 0; i < STRING_SIZE; i++)
似乎是个坏主意。 我假设 STRING_SIZE 是在#define
中设置的一些固定数字,它不起作用,因为输入字符串可以更短也可以更长。
相反,我建议您使用指针来迭代字符串,即初始化指针以指向字符串的开头,并在每个循环中递增指针并继续循环,直到您看到字符串终止。
这可能看起来像:
#include <stdio.h>
int is_whitespace(char c)
{
// Check for space or tab
return (c == ' ' || c == '\t');
}
int get_number_of_words(char* input_string)
{
int counter = 0;
// Make p point to start of string
char* p = input_string;
// Remove whitespaces, i.e. look for next word or end-of-string
while (*p && is_whitespace(*p)) ++p;
while(*p)
{
++counter;
// Continue down the string until a whitespace or end-of-string is found
while(*p && !is_whitespace(*p)) ++p;
// Remove whitespaces, i.e. look for next word or end-of-string
while (*p && is_whitespace(*p)) ++p;
}
return counter;
}
int main()
{
char* str1 = "some text";
printf("%s %d\n", str1, get_number_of_words(str1));
char* str2 = " some text ";
printf("%s %d\n", str2, get_number_of_words(str2));
char* str3 = "some\ttext";
printf("%s %d\n", str3, get_number_of_words(str3));
char* str4 = "\tsome\t\ttext\t\t";
printf("%s %d\n", str4, get_number_of_words(str4));
return 0;
}
Output:
some text 2
some text 2
some text 2
some text 2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.