如何在没有标点符号的情况下打印整个句子? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我无法在字符串中打印整个输出。

我所知道的是%s应该像循环一样工作,例如printf(“%s”,str);与puts(str)相同;

#include <stdio.h>
#include <string.h>


int main (){
    char str[]="Hello:, student; how are you? This task is easy!";
    char *token;
    char del[] = ", ; : ? !", cp[80];
    int count;
    strcpy(cp, str);
    token = strtok(str, del);
    count = 0;
    while( token != NULL )
    {
        printf("%s\n", token);

        token = strtok(NULL, del);
        count++;
        }   
    strtok(str, del);   
    printf("Your sentence has %d words\n", count); 
    puts("The sentence without punctuation charachters is: \n ");
    puts(str); // This should where it show me the output
    return 0 ;
}

//我试着遵循我必须以这种形式编写此代码的指令。 //这是我想要的输出

你好

学生

怎么样

这个

任务

简单

你的句子有11个单词没有标点符号的句子是:你好学生你好吗,这个任务很简单

//我得到的是(忽略每个单词之间的额外行)

你好

学生

怎么样

这个

任务

简单

你的句子有11个单词没有标点符号的句子是:你好

c
1个回答
0
投票

strtok(str, del);修改了第一个在内部添加空字符的参数,这就是为什么当你在strtok的调用之后打印str时你只得到第一个令牌

你保存字符串做strcpy(cp, str);,但你不使用它,你也希望80足够......

将单词放在cp然后打印它的提议:

#include <stdio.h>
#include <string.h>

int main (){
  char str[]="Hello:, student; how are you? This task is easy!";
  char *token;
  char del[] = ", ; : ? !", cp[sizeof(str) + 1];
  int count;
  size_t pos = 0;

  token = strtok(str, del);
  count = 0;
  while( token != NULL )
  {
    printf("%s\n", token);
    strcpy(cp + pos, token);
    pos += strlen(token);
    cp[pos++] = ' ';
    token = strtok(NULL, del);
    count++;
  }
  cp[(pos == 0) ? 0 : (pos - 1)] = 0;
  printf("Your sentence has %d words\n", count); 
  puts("The sentence without punctuation characters is:");
  puts(cp); // This should where it show me the output
  return 0 ;
}

编译和执行:

pi@raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi@raspberrypi:/tmp $ ./a.out
Hello
student
how
are
you
This
task
is
easy
Your sentence has 9 words
The sentence without punctuation characters is:
Hello student how are you This task is easy
pi@raspberrypi:/tmp $ 
© www.soinside.com 2019 - 2024. All rights reserved.