我写了一段代码来计算一个字符串由多少个字组成。
我已经尝试了多种输入,大多数输入都是正确的,但也有一些情况表明我的程序有一个基本的逻辑缺陷。例如,如果我设置了一个空字符串,输出将错误地是1,如果我在字符串的最后添加了空格,出于某种原因,我不知道输出将是1+字符串中的实际字数,而我的代码显然表明,我想删除所有的空格。
我的程序基本上是在字符串中进行的,但不幸的是,在字符串的最后并没有进行。我很清楚我的函数有问题,但我不知道是什么问题。而且我知道借助外部的库可能更容易实现,但我被要求用纯基本的代码来实现它。
这就是我目前所掌握的情况。
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;
}
我给你举几个输入和输出字符串的例子 :
"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;
}
输出:
some text 2
some text 2
some text 2
some text 2