[英]C - Counting words in a string
我一直在尝试做一个计算C语言字符串中单词数量的函数。但是,在某些casas中(如示例中的那个),它应该返回0而不是1 ...关于可能的任何想法错误?
#import <stdio.h>
int contaPal(char s[]) {
int r;
int i;
r = 0;
for (i = 0; s[i] != '\0'; i++) {
if (s[i] == '\n')
r = r + 0;
if (s[i] != ' ' && s[i + 1] == ' ' && s[i + 1] != '\0')
r++;
if (s[i] != ' ' && s[i + 1] == '\0') {
r++;
}
}
return r;
}
int main () {
char s[15] = { ' ', '\n', '\0' };
printf("Words: %d \n", (contaPal(s)));
return 0;
}
您不应将'\\n'
与其他空格字符区别对待。
这是一个简单的版本:
#include <ctype.h>
#include <stdio.h>
int contaPal(const char *s) {
int count = 0, hassep = 1;
while (*s) {
if (isspace((unsigned char)*s) {
hassep = 1;
} else {
count += hassep;
hassep = 0;
}
s++;
}
return count;
}
int main(void) {
char s[] = " \n";
printf("Words: %d\n", contaPal(s));
return 0;
}
我想这个词是除空格字符之外的任何字符序列。
您的函数返回1,因为遇到这种情况时,对于提供的字符串,遇到换行符时,变量r
会增加
if (s[i] != ' ' && s[i + 1] == '\0') {
r++;
}
因此,函数实现是错误的。
可以按照演示程序中所示的以下方式进行定义
#include <stdio.h>
#include <ctype.h>
size_t contaPal( const char s[] )
{
size_t n = 0;
while ( *s )
{
while ( isspace( ( unsigned char )*s ) ) ++s;
n += *s != '\0';
while ( *s && !isspace( ( unsigned char )*s ) ) ++s;
}
return n;
}
int main(void)
{
char s[] = { ' ', '\n', '\0' };
printf( "Words: %zu\n", contaPal( s ) );
return 0;
}
如您所料,它的输出是
Words: 0
使用现有字符测试功能的简单图示:
int main(void)
{
int cnt = 0;
int numWords = 0;
BOOL trap = 0; //start count only after seeing a word
char *sentence = "This is a sentence, too long.";
//char *sentence2 = " ";//tested for empty string also
while (*sentence != '\0')
{
if ( isalnum (*sentence) ) //word is found, set trap and start count
{
sentence++; //alpha numeric character, keep going
trap = 1;
}
else if ( (( ispunct (*sentence) ) || ( isspace(*sentence) )) && trap)
{ //count is started only after first non delimiter character is found
numWords++;
sentence++;
while(( ispunct (*sentence) ) || ( isspace(*sentence) ))
{ //handle sequences of word delimiters
sentence++;
}
}
else //make sure pointer is increased either way
{
sentence++;
}
}
return 0;
}
该行:
if (s[i] != ' ' && s[i + 1] == ' ' && s[i + 1] != '\0')
r++;
当您查看'\\n'
时,完全匹配大小写。
您应该使用if ... else if ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.