繁体   English   中英

如何将字符串添加到 C 中的字符串数组?

[英]How can I add a string to an array of strings in C?

我有一个字符串“token”和一个空的字符串数组“arr”。 我想将令牌添加到 arr 的第一个索引。 我尝试过arr[0][0] = token ,但这仅适用于字符,我也尝试过arr[0] = token但这会引发错误“表达式必须是可修改的左值”。 我的完整程序是:

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

char arr[100][100] = {};
char *token = strtok(StringToBeSplit, " ");
int i = 0;

while(token != NULL) {
    arr[0] = token;
    printf("%s\n", token);
    token = strtok(NULL, " ");
    i++;
}

我应该怎么办?

您需要复制字符串而不是分配它。 您的代码的另一个问题是只有数组的元素 [0] 被填充

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

char arr[100][100] = {};
char *token = strtok("split this string", " ");
int i = 0;

while(token != NULL) {
    strcpy(arr[i], token);
    printf("%s\n", token);
    token = strtok(NULL, " ");
    i++;
}

// At this point, i contains the number of tokens.

如果您从 -1 开始 i 并在 strcpy 之前递增,那么 i 将是最后一个元素的索引。

您需要避免将字符串文字分配给 strtok。 基本上使用 strcpy 将令牌复制到数组并按照先前答案的建议递增数组。 像这样的东西: -

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

int main(){

char arr[100][100] = {};
char str[] = "Split this string";
char sep[] = " ";
char *token = strtok(str, sep);
int i = 0;
while(token != NULL){
    strcpy(arr[i], token);
    token = strtok(NULL, sep);
    i++;
}

//Test If it can print the strings
for(int j = 0; j < i; j++)
    printf("%s\n", arr[j]);

 }

暂无
暂无

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

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