将字符串分割使用C每一个空格 [英] Split string in C every white space

查看:427
本文介绍了将字符串分割使用C每一个空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C编写一个程序,在一个单独的行显示一个完整的句子(作为输入)的每个字。这是我迄今所做的:


 无效处理(字符*缓冲液);
INT get_words(字符*缓冲液);诠释主(){
    字符的buff [100];    的printf(sizeof的%d个\\ nstrlen%d个\\ N的sizeof(BUFF),strlen的(BUFF)); //调试原因    bzero(BUFF,sizeof的(BUFF));    的printf(给我的文字:\\ n);
    与fgets(BUFF,sizeof的(BUFF),标准输入);    操作(BUFF);
    返回0;
}诠释get_words(字符*缓冲区){//功能,获取的字数,通过计算的空间。
    诠释计数;
    INT单词计数= 0;
    焦炭CH;    为(计数= 0; COUNT< strlen的(缓冲);计数++){
        CH =缓冲[统计]
        如果((ISBLANK(CH))||(缓冲[统计] =='\\ 0')){//如果字符是空白的,或空字节加1到wordcounter
            单词计数+ = 1;
        }
    }
    的printf(%d个\\ n \\ n,单词计数);
    返回单词计数;
}空操作(字符*缓冲区){
    INT字= get_words(缓冲);
    字符* newbuff [文字]
    字符* PTR;
    诠释计数= 0;
    INT COUNT2 = 0;
    焦炭CH ='\\ n';    PTR =缓冲;
    bzero(newbuff,sizeof的(newbuff));    为(计数= 0; COUNT< 100;计数++){
        CH =缓冲[统计]
        如果(ISBLANK(CH)||缓冲[统计] =='\\ 0'){
            缓冲[统计] ='\\ 0';
            如果((newbuff [COUNT2] =(字符*)malloc的(strlen的(缓冲)))== NULL){
                的printf(MALLOC错误。\\ n!);
                出口(-1);
            }
            的strcpy(newbuff [COUNT2],PTR);
            的printf(\\ n%S \\ n,newbuff [COUNT2]);
            PTR =安培;缓冲区[计数+ 1];
            COUNT2 ++;
        }
    }
}


虽然输出是我想要的,我都有所显示的最后一句话后还真不少黑色的空间,而malloc()函数返回NULL所以malloc的错误!显示在端。
我可以理解,有我的malloc()实现了一个错误,但我不知道它是什么。

有另一种更优雅的 - 通常更好的方式来做到这一点。

先谢谢了。


解决方案

<一个href=\"http://www.cplusplus.com/reference/clibrary/cstring/strtok/\">http://www.cplusplus.com/reference/clibrary/cstring/strtok/

看看这一点,并使用空白字符作为分隔符。如果你需要更多的提示让我知道。

从网站:

 的char * strtok的(字符*海峡,为const char *分隔符);


  

在第一次呼叫,该函数需要一个C字符串作为论据海峡,其第一个字符作为起始位置扫描令牌。在随后的电话,该函数需要一个空指针和使用位置最后一个令牌作为扫描新的起点位置结束后的权利。


  
  

在str的终止空字符在调用函数strtok被发现,该函数的所有后续调用(带一个空指针作为第一个参数)返回一个空指针。


  
  

参数


  
  

      
  • STR
      

        
    • C字符串截断。

    •   
    • 请注意,此字符串是由被破碎成较小的字符串(令牌)进行修改。
        Alternativelly [原文],一个空指针可以指定,在这种情况下,功能继续扫描其中previous成功调用该函数结束。

    •   

  •   
  • 分隔符
      

        
    • 包含分隔符的C字符串。

    •   
    • 这可以从一个电话而异。

    •   

  •   

  
  

返回值


  
  

一个指向字符串中找到的最后一个令牌。
  如果没有留下标记检索,则返回一个空指针。


  
  

示例


  / * strtok的例子* /
#包括LT&;&stdio.h中GT;
#包括LT&;&string.h中GT;诠释的main()
{
  烧焦海峡[] = - 这,样本串;
  字符* PCH;
  的printf(分割字符串\\%s \\的成标记:\\ n,STR);
  PCH = strtok的(STR,.-);
  而(PCH!= NULL)
  {
    的printf(%S \\ n,PCH);
    PCH =的strtok(NULL,.-);
  }
  返回0;
}

I want to write a program in C that displays each word of a whole sentence (taken as input) at a seperate line. This is what i have done so far:


void manipulate(char *buffer);
int get_words(char *buffer);

int main(){
    char buff[100];

    printf("sizeof %d\nstrlen %d\n", sizeof(buff), strlen(buff));   // Debugging reasons

    bzero(buff, sizeof(buff));

    printf("Give me the text:\n");
    fgets(buff, sizeof(buff), stdin);

    manipulate(buff);
    return 0;
}

int get_words(char *buffer){                                        // Function that gets the word count, by counting the spaces.
    int count;
    int wordcount = 0;
    char ch;

    for (count = 0; count < strlen(buffer); count ++){
        ch = buffer[count];
        if((isblank(ch)) || (buffer[count] == '\0')){                   // if the character is blank, or null byte add 1 to the wordcounter
            wordcount += 1;
        }
    }
    printf("%d\n\n", wordcount);
    return wordcount;
}

void manipulate(char *buffer){
    int words = get_words(buffer);
    char *newbuff[words];
    char *ptr;
    int count = 0;
    int count2 = 0;
    char ch = '\n';

    ptr = buffer;
    bzero(newbuff, sizeof(newbuff));

    for (count = 0; count < 100; count ++){
        ch = buffer[count];
        if (isblank(ch) || buffer[count] == '\0'){
            buffer[count] = '\0';
            if((newbuff[count2] = (char *)malloc(strlen(buffer))) == NULL) {
                printf("MALLOC ERROR!\n");
                exit(-1);
            }
            strcpy(newbuff[count2], ptr);
            printf("\n%s\n",newbuff[count2]);
            ptr = &buffer[count + 1];
            count2 ++;
        }
    }
}


Although the output is what i want, i have really many black spaces after the final word displayed, and the malloc() returns NULL so the MALLOC ERROR! is displayed in the end. I can understand that there is a mistake at my malloc() implementation but i do not know what it is.

Is there another more elegant - generally better way to do it?

Thanks in advance.

解决方案

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.

From the website:

char * strtok ( char * str, const char * delimiters );

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.

Parameters

  • str
    • C string to truncate.
    • Notice that this string is modified by being broken into smaller strings (tokens). Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
  • delimiters
    • C string containing the delimiter characters.
    • These may vary from one call to another.

Return Value

A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.

Example

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[] ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}

这篇关于将字符串分割使用C每一个空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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