Breaking down string and storing it in array

前端 未结 2 775
小鲜肉
小鲜肉 2021-02-03 13:40

I want to break down a sentence and store each string in an array. Here is my code:

#include 
#include 

int main(void)
{
    int         


        
2条回答
  •  说谎
    说谎 (楼主)
    2021-02-03 14:15

    Have a look at the example in the docs:

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

    ...where...

    str - C string to truncate. The contents of this string are modified and broken into smaller strings (tokens). Alternativelly, 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 delimiters. 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.

    You need that first string to me modifiable and you need to allocate memory for the outputs e.g.

    int main(void)
    {
        int i = 0;
        const int numOfStrings = 128;
        char* strArray[numOfStrings];
        char writablestring[]= "The C Programming Language";
        char *token = strtok(writablestring, " ");
    
        for( int j = 0; j < numOfStrings; j++ )
        {
            strArray[j] = new char[40];
        }
    
        while(token != NULL)
        {
            strcpy(strArray[i], token);
            printf("[%s]\n", token);
            token = strtok(NULL, " ");
            i++;
        }
        return 0;
    }
    

提交回复
热议问题