繁体   English   中英

如何从C中的给定行创建字符串数组?

[英]How to create an array of strings from a given line in C?

char a[100]="You are welcome";

现在如何将这一行中的单词变成字符串数组?

char b[5][20];
strcpy(b[0],"you");
strcpy(b[1],"are");
strcpy(b[2],"welcome");

这样,我们可以使字符串数组。

但是我想动态地进行任何输入吗?

请帮忙...

strtok是您的朋友:

char a[] = "You are welcome";
char b[5][20] = {{0}};
char *pch;

pch = strtok( a," \t" );
int i = 0;
while( NULL != pch && i < 5)
{
    strcpy(b[i++], pch);
    pch = strtok( NULL, " \t\n" );
}

for( i = 0; i < 5; i++ )
{
    if( strlen(b[i]) > 0 )
    {
        printf( "b[%d] = %s\n", i, b[i] );
    }
}

不要忘记#include <string.h>


正如David C. Rankin指出的那样。 我们可以通过只检查第一个字符而不是\\0来消除strlen 因此,这将是一个更好的解决方案(请注意, strtok处理的主while循环保持不变)。

i = 0; 
while (*b[i]) 
{ 
    printf( "b[%d] = %s\n", i, b[i] ); 
    i++; 
}

参考:strtok

您可以在while循环中使用“ scanf”代替“ printf”,并将值存储在第二个数组中(在您的情况下为b)

 while (pch != NULL)   {
     printf ("%s\n",pch);
     pch = strtok (NULL, " ,.-");   }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM