如何省略字符串中的空格

时间:2013-02-05 18:59:22

标签: c string spaces

我需要编写一个程序,它将读入一个句子并输出句子中的单词数。我已完成程序,但问题是我的程序正在计算单词之间的空格作为字符。如何省略这些空格,只显示字符串中的单词数?我以为我需要某种类型的循环,但我不知道如何执行它。

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define pause system("pause")

main() {
char mystring[155];
int counter = 0;

printf("Enter your name: ");
scanf("%[^\t\n]", &mystring); 
printf("Your name is %s\n", mystring);

// find out the number of characters in the string
counter = strlen(mystring); 
printf("There are %i words in the sentence. \n", counter);

// find out how many WORDS are in the sentence. Omit spaces



pause;
} // end of main

2 个答案:

答案 0 :(得分:0)

同样,正如有人已经说过的那样,使用strtok。如果您需要了解更多信息, http://www.cplusplus.com/reference/cstring/strtok/

如果你想在不使用任何现有API的情况下这样做(我不知道你为什么要这样做,除非它是一个类项目),然后创建一个简单的算法,其中包含一个遍历字符串并跳过空格的指针递增计数。

正如人们之前所说,这对你来说是一个很好的练习,所以不要问代码。并且总是谷歌..

答案 1 :(得分:0)

你的功能看起来像这样:

_getNumberOfWords(char[] string) {
    int count = 0;
    for (int i=0; string[i] != '\0'; i++) {
        if (string[i] == " ") {
        for (int j=i; string[j] != '\0'; j++) {
            // This is to handle multiple spaces
            if (string[j] != " ") break;
        }
        count++;
    }
    return count;
}

你也可以尝试做:

char * strtok ( char * string, const char * " " );