简体   繁体   English

C 包含要放入字符串数组的子字符串的字符数组

[英]C char array containing substrings to be put into array of strings

Given char *line = {'a','\0','b','\0', 'c', '\0'}给定char *line = {'a','\0','b','\0', 'c', '\0'}

how would you make it so that char **str_arr would point/be assigned to all the substrings within line ?您将如何使char **str_arr指向/分配给line内的所有子字符串?

str_arr[str_arr_index] = line works only for the first substring, but anything after it is just NULL str_arr[str_arr_index] = line仅适用于第一个 substring,但之后的任何内容都只是 NULL

str_arr = malloc(3 * sizeof (char *));
str_arr[0] = &line[0];
str_arr[1] = &line[2];
str_arr[2] = &line[4];

There is no way to do it programmatically because there is no way to know how many substrings line contains.无法以编程方式执行此操作,因为无法知道line包含多少子字符串。 (Just as there is no way from the output of the code above to know that str_arr now has three pointers to three substrings.) (就像从上面代码的 output 无法知道str_arr现在有三个指向三个子字符串的指针一样。)

First of all the statement首先声明

char *line = {'a','\0','b','\0', 'c', '\0'}

is not valid this can only be an array like the following无效,这只能是如下所示的数组

char *line = {'a','\0','b','\0', 'c', '\0'}

Here is a code sample that generates substrings这是一个生成子字符串的代码示例

#include "stdlib.h"
#include "stdio.h"

int main()
{   
    char line[] = {'a','\0','b','\0', 'c', 'v', '\0', 'd', 'e', '\0'};
    
    int size = sizeof(line) / sizeof(char);
    int count = 0;
    int start = 0;
    
    char *str_arr[size];   // the size can be optimized with reallocs or by counting the terminatin chars in the line
    
    for (int i = 0; i < size; ++i) {
        if (line[i] == '\0') {
            str_arr[count] = &line[start];
            printf("string #%d -> %s \n", count + 1, str_arr[count]);
            start = i + 1;
            ++count;
        }
    }   
    
    return 0;
}

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

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