如何将字符串分割成单词?

时间:2018-08-08 14:38:33

标签: c arrays string argv argc

我正在尝试将字符串拆分为单词。谁能在不使用strtokmain以外的其他功能的情况下帮助我实现它?

void main()
{
    int i;
    int myargc = 1;
    char *myargv[256];
    char buff[100];
    int len = 0;
    char string[256];
    int j = 0;

    printf("Enter text: ");
    gets(buff);

    for(i = 0; buff[i] != '\0'; i++){
        len++;
    }

    for(i = 0; i < len; i++)
    {
        if(buff[i]!=' ' && buff[i+1]==' ')
        {
            myargc++;
        }
    }
    printf("myargc %d\n",myargc);

    **for(i = 0; i < len; i++){
        if(buff[i] != ' '){
            string[j++] = buff[i];
        }
        if(buff[i] != ' ' && buff[i] == ' '){
            string[j++] = '\0';
            j = 0;
        }
        if(buff[i] == '\0'){
            break;
        }
    }**
    for(i = 0; i < myargc - 1; i++){
        myargv[i] = string;
        printf("argv[%d]\t%s\n", i, myargv[i]);
    }
}

例如,当我输入“ a b c”时,我的输出如下所示:

myargc 3
argv[0] abc
argv[1] abc
argv[2] abc

1 个答案:

答案 0 :(得分:0)

所以这是我的解决方案,不确定是否是最佳选择,但在单词之间也留有更多空格。

#include <stdio.h>
#include <stdlib.h>

void main()
{
    int i;
    int myargc = 1;
    char **myargv;
    char buff[100];
    int len = 0;
    char string[256];
    int j = 0, k =0;

    printf("Enter text: ");
    gets(buff);

    for(i = 0; buff[i] != '\0'; i++){
        len++;
    }

    for(i = 0; i < len; i++)
    {
        if(buff[i]!=' ' && buff[i+1]==' ')
        {
            myargc++;
        }
    }
    printf("myargc %d\n",myargc);

    //allocating 256 bytes * number of words    
    myargv = (char**)malloc(myargc*sizeof(char*));
    for(i = 0; i < myargc; i++){
        myargv[i] = (char*)malloc(256*sizeof(char));
    }

    //iterating until the ending character
    for(i = 0; i <= len; i++){
        //building word
        if(buff[i] != ' ' && buff[i] != 0)
        {   
            string[j++] = buff[i];
        }

        //copying word to corresponding array
        else if((buff[i] == ' ' && buff[i+1] != ' ') || (buff[i] == 0))
        {
            for(int z = 0; z < j; z++){
                myargv[k][z] = string[z];
            }

            myargv[k++][j] = '\0';
            j = 0;
        }

        //skipping more spaces in a row
        else continue;
    }


    for(i = 0; i < myargc; i++){
        printf("argv[%d]\t%s\n", i, myargv[i]);
    }

    }