【问题标题】:How to omit the spaces in a string如何省略字符串中的空格
【发布时间】:2013-02-05 18:59:22
【问题描述】:

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

#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

【问题讨论】:

  • 提示:认为你需要一个循环并计算单词,跳过标点符号,但我不会为你编写程序。
  • 单词或字符?你说的话,但你的代码似乎在计算字符。

标签: c string spaces


【解决方案1】:

同样,正如有人已经说过的,使用 strtok。如果您需要进一步了解它, http://www.cplusplus.com/reference/cstring/strtok/

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

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

【讨论】:

    【解决方案2】:

    你的函数看起来像这样:

    _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 * " " );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 2017-01-03
      • 1970-01-01
      • 2015-12-17
      • 2015-09-02
      相关资源
      最近更新 更多