将单词读入字符串数组?

时间:2021-01-29 15:45:34

Currently I'm reading each character from the user and storing it into a char array called str. From there I'm trying to use a pointer to loop through the string until it sees a space, once a space is seen I want to take the characters already and create an array of strings. Is that possible? Reasons why I'm doing this is because I later want to use an execlp function to execute a process after my initial program was executed. 将单词读入字符串数组?

目前我正在读取用户的每个字符并将其存储到名为str的char数组中。从那里我试图使用一个指针循环遍历字符串,直到它看到一个空格,一旦看到一个空格我想要已经取出字符并创建一个字符串数组。那可能吗?我这样做的原因是因为我后来想要在执行初始程序后使用execlp函数来执行进程。

1 个解决方案

#1


0  

If you want to split the string into tokens separated by delimiters you could use the strtok function.

如果要将字符串拆分为由分隔符分隔的标记,可以使用strtok函数。

An example would be:

一个例子是:

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

int main(void)
{
    int i, n;
    char str[] = "Hello World";
    char *token[4], *act_token;

    token[0] = strtok(str, " ");
    n=1;
    while(n<4 && (act_token=strtok(NULL, " ")))
    {
        token[n] = act_token;
        n++;
    }

    for(i=0;i<n;i++)
    {
        printf("%d: %s\n", i, token[i]);
    }

    return 0;
}

#1


0  

If you want to split the string into tokens separated by delimiters you could use the strtok function.

如果要将字符串拆分为由分隔符分隔的标记,可以使用strtok函数。

An example would be:

一个例子是:

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

int main(void)
{
    int i, n;
    char str[] = "Hello World";
    char *token[4], *act_token;

    token[0] = strtok(str, " ");
    n=1;
    while(n<4 && (act_token=strtok(NULL, " ")))
    {
        token[n] = act_token;
        n++;
    }

    for(i=0;i<n;i++)
    {
        printf("%d: %s\n", i, token[i]);
    }

    return 0;
}