gpt4 book ai didi

c - 如何省略字符串中的空格

转载 作者:行者123 更新时间:2023-11-30 20:41:27 26 4
gpt4 key购买 nike

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

#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

最佳答案

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

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

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

关于c - 如何省略字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14714860/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com