[英]convert an string with multiple words to an array of char
Imagine I have the following string: 假设我有以下字符串:
char input[] = "this is an example";
I want to take this string and make each word an entry in an array, how could I get this into an array like this: 我想使用此字符串并将每个单词作为数组中的一个条目,如何将其放入这样的数组中:
char inputArray[] = {"this","is","an","example"};
Either you do not know exactly what you want or you want the following:) 您可能不完全知道自己想要什么,或者您想要以下内容:)
#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;
}
The program output is 程序输出为
this
is
an
example
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.