将具有多个单词的字符串转换为char数组

时间:2016-06-22 14:31:04

标签: c arrays string char

想象一下,我有以下字符串:

INSERT INTO Test_id_isbnyear    
SELECT I.id, I.isbn, Y.year    
FROM Prod_id_isbn I     
LEFT JOIN Prod_id_year Y ON I.ID = Y.I_ID;

我想取这个字符串并使每个单词成为数组中的一个条目, 我怎么能把它变成这样的数组:

char input[] = "this is an example";

1 个答案:

答案 0 :(得分:2)

要么你不确切地知道你想要什么,要么你想要以下内容:)

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

int main(void) 
{
    char input[] = "this is an example";

    size_t n = 0;

    for ( char *p = input; *p;  )
    {
        while ( isspace( ( unsigned char )*p ) ) ++p;

        if ( *p )
        {
            ++n;
            while ( *p && !isspace( ( unsigned char )*p ) ) ++p;
        }
    }

    char * inputArray[n];

    size_t i = 0;
    for ( char *p = strtok( input, " \t" ); p != NULL; p = strtok( NULL, " \t" ) ) inputArray[i++] = p;

    for ( i = 0; i < n; i++ ) puts( inputArray[i] );

    return 0;
}

程序输出

this
is
an
example