【发布时间】:2015-05-07 04:38:41
【问题描述】:
编写一个计算字符串中单词数的基本程序。我已经更改了原始代码以说明单词之间的多个空格。通过将一个变量设置为当前索引,将一个变量设置为前一个索引并比较它们,我可以说“如果当前索引是空格,但前一个索引包含空格以外的内容(基本上是说一个字符),那么增加字数”。
int main(int argc, const char * argv[]) {
@autoreleasepool {
//establishing the string that we'll be parsing through.
NSString * paragraph = @"This is a test paragraph and we will be testing out a string counter.";
//we're setting our counter that tracks the # of words to 0
int wordCount = 0;
/*by setting current to a blank space ABOVE the for loop, when the if statement first runs, it's comparing [paragraph characterAtIndex:i to a blank space. Once the loop runs through for the first time, the next value that current will have is characterAtIndex:0, while the if statement in the FOR loop will hold a value of characterAtIndex:1*/
char current = ' ';
for (int i=0; i< paragraph.length; i++) {
if ([paragraph characterAtIndex:i] == ' ' && (current != ' ')) {
wordCount++;
}
current = [paragraph characterAtIndex:i];
//after one iteration, current will be T and it will be comparing it to paragraph[1] which is h.
}
wordCount ++;
NSLog(@"%i", wordCount);
}
return 0;
}
我尝试添加“或”语句来说明分隔符,例如“;” “,“ 和 ”。”而不是只看一个空间。它没有用......从逻辑上讲,我能做什么来解释不是字母的任何东西(但最好将它限制为这四个分隔符 - . , ; 和空格。
【问题讨论】:
-
你考虑过没有任何分隔符的单个单词的边缘情况吗?
-
@hiandbaii 如果“段落”字符串只有一个没有分隔符的单词,我的代码运行良好。
-
为什么不使用
strtok,添加任意数量的分隔符,然后循环调用直到完成?
标签: objective-c c delimiter word-count