将字存储在char数组C语言中

时间:2021-04-11 15:44:23

I have this code:

我有这个代码:

char *pch;
pch = strtok(texto," ");

while (pch != NULL)
{
  pch = strtok (NULL, " ");
}

My "texto" variable have something like "This is my text example".

我的“texto”变量有类似“这是我的文本示例”。

And i need to store each value comming from pch in while, in an array of characteres, but i really dont know how to do it.

而且我需要存储每个来自pch的值,而在一系列的characteres中,但我真的不知道该怎么做。

I need something like that, each value in array will have a word, so:

我需要这样的东西,数组中的每个值都有一个单词,所以:

"This is my text example".

“这是我的文字示例”。

Array[0][20] = This;

Array[1][20] = is;

Array[2][20] = my;

Array[3][20] = text;

Array[4][20] = example;

The pch in while having all these words already split, but I don't know how to add into a char array, or how I will declare him too.

虽然所有这些单词已经分裂,但是我不知道如何添加到char数组中,或者我将如何声明他。

2 个解决方案

#1


2  

Consider the following example:

请考虑以下示例:

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

#define MAXSTRLEN 20
#define MAXWORD 6

int main(void)
{
    char arr[MAXWORD][MAXSTRLEN+1] = {0};
    char str[] ="This is my text example";
    char *pch;
    int i = 0;
    pch = strtok (str," ");
    while (pch != NULL && i < MAXWORD)
    {
        strncpy(arr[i++], pch, MAXSTRLEN);
        pch = strtok (NULL, " ");
    }
    return 0;
}

#2


0  

This should work. Use strcpy to copy pch to character array.

这应该工作。使用strcpy将pch复制到字符数组。

char str[] ="This is my text example";
char *pch;
int i = 0;
pch = strtok (str," ");
char a[10][20];
while (pch != NULL)
{   
  strcpy(a[i++], pch);
  pch = strtok (NULL, " ");
}

And as @stackptr has suggested dont use strtok and instead use strtok_r . For more info on this.

正如@stackptr建议不要使用strtok而是使用strtok_r。有关这方面的更多信息。

#1


2  

Consider the following example:

请考虑以下示例:

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

#define MAXSTRLEN 20
#define MAXWORD 6

int main(void)
{
    char arr[MAXWORD][MAXSTRLEN+1] = {0};
    char str[] ="This is my text example";
    char *pch;
    int i = 0;
    pch = strtok (str," ");
    while (pch != NULL && i < MAXWORD)
    {
        strncpy(arr[i++], pch, MAXSTRLEN);
        pch = strtok (NULL, " ");
    }
    return 0;
}

#2


0  

This should work. Use strcpy to copy pch to character array.

这应该工作。使用strcpy将pch复制到字符数组。

char str[] ="This is my text example";
char *pch;
int i = 0;
pch = strtok (str," ");
char a[10][20];
while (pch != NULL)
{   
  strcpy(a[i++], pch);
  pch = strtok (NULL, " ");
}

And as @stackptr has suggested dont use strtok and instead use strtok_r . For more info on this.

正如@stackptr建议不要使用strtok而是使用strtok_r。有关这方面的更多信息。