如何用C中的空格分割句子? [英] How to split a sentence by white space in C?

查看:89
本文介绍了如何用C中的空格分割句子?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输入一个句子。将句子分成单词。我想将单词存储到数组中。打印单词。



示例:



句子=学习C程序



输出=

数组[0] =学习

数组[1] = C

数组[ 2] =程序。



请帮帮我。



我尝试过的:



Input a sentence. Split sentence into words. I want to store words into array. Print array of words.

Example:

Sentence = learning C Program

output=
array[0]=learning
array[1]=C
array[2]=Program.

Please help me.

What I have tried:

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

int main ()
{
	char str[] ="";
	printf("\nEnter sentence = ");
	scanf("%s",&str);
    char * pch;
   	pch = strtok (str," ,.-");
 	while (pch != NULL)
  	{
    	printf ("%s\n",pch);
    	pch = strtok (NULL, " ,.-");
 	 }
  return 0;
}

推荐答案

我们不做你的功课:这是有原因的。它就是为了让你思考你被告知的事情,并试着理解它。它也在那里,以便您的导师可以识别您身体虚弱的区域,并将更多的注意力集中在补救措施上。



亲自尝试,你可能会发现它不是和你想的一样困难!



如果遇到具体问题,请询问相关问题,我们会尽力提供帮助。但是我们不会为你做这一切!
We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!

If you meet a specific problem, then please ask about that and we will do our best to help. But we aren't going to do it all for you!


Quote:

char str [] =;

char str[] ="";

您正在分配1个字符的数组。收到用户的一句话太小了。







You are allocating a 1-character array. Too small for receiving a sentence from the user.



Quote:

scanf(%s,& str);

scanf("%s",&str);

不幸的是,句子中的第一个空格会停止 scanf 进一步处理,同时你需要从用户那里得到一整行。



试试,例如:

Unfortunately the first blank in the sentence stops scanf further processing, while you need to get a whole line from the user.

Try, for instance:

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


int main ()
{
  char str[0x100];
  printf("\nEnter sentence = ");
  fgets(str, sizeof(str), stdin);
  char * pch;
  pch = strtok (str," ,.-");
  while (pch != NULL)
    {
      printf ("%s\n",pch);
      pch = strtok (NULL, " ,.-");
   }
  return 0;
}


这篇关于如何用C中的空格分割句子?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆