简体   繁体   English

将字符串转换为 C 中的字符串数组

[英]Convert String into Array of Strings in C

I'm trying to divide a string of alphabetically sorted words char *str = "a/apple/arm/basket/bread/car/camp/element/..." into an array of strings alphabetically like so:我正在尝试将一串按字母顺序排序的单词char *str = "a/apple/arm/basket/bread/car/camp/element/..."分成按字母顺序排列的字符串数组,如下所示:

arr[0] = "a/apple/arm"
arr[1] = "basket/bread"
arr[2] = "car/camp"
arr[3] = ""
arr[4] = "element"
...

I'm not very skilled in C, so my approach was going to be to declare:我对 C 不是很熟练,所以我的方法是声明:

char arr[26][100]; 
char curr_letter = "a";

and then iterate over each char in the string looking for "/" follow by char,= curr_letter.然后遍历字符串中的每个字符以查找“/”,然后是 char,= curr_letter。 then strcpy that substring to the correct location.然后将 substring strcpy 到正确的位置。

I'm not sure if my approach is very good, let alone how to implement it properly.我不确定我的方法是否很好,更不用说如何正确实施了。 Any help would be greatly appreciated!任何帮助将不胜感激!

So we basically loop through the string, and check if we found the "split character' and we also check that we didn't find the 'curr_letter' as the next character.所以我们基本上循环遍历字符串,检查是否找到了“拆分字符”,还检查了没有找到下一个字符“curr_letter”。

We keep track of the consumed length, the current length (used for memcpy later to copy the current string to the array).我们跟踪消耗的长度,当前长度(用于 memcpy 稍后将当前字符串复制到数组中)。

When we find a position where we can add the current string to the array, we allocate space and copy the string to it as the next element in the array.当我们找到一个 position 可以将当前字符串添加到数组中时,我们分配空间并将字符串复制到它作为数组中的下一个元素。 We also add the current_length to consumed, and the current_length is reset.我们还将 current_length 添加到消费中,并且 current_length 被重置。

We use due_to_end to find out if we have a / in the current string, and remove it accordingly.我们使用due_to_end来确定当前字符串中是否有/ ,并相应地删除它。

Try:尝试:

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

int main() {
        char *str = "a/apple/arm/basket/bread/car/camp/element/...";
        char split_char = '/';
        char nosplit_char = 'a';

        char **array = NULL;
        int num_elts = 0;

        // read all the characters one by one, and add to array if 
        // your condition is met, or if the string ends
        int current_length = 0; // holds the current length of the element to be added
        int consumed = 0; // holds how much we already added to the array
        for (int i = 0; i < strlen(str); i++) { // loop through string
                current_length++; // increment first
                int due_to_end = 0;
                if ( ( str[i] == split_char // check if split character found
                    && ( i != (strlen(str) - 1) // check if its not the end of the string, so when we check for the next character, we don't overflow
                    && str[i + 1] != nosplit_char ) ) // check if the next char is not the curr_letter(nosplit_char)
                   || (i == strlen(str) - 1 && (due_to_end = 1))) { // **OR**, check if end of string
                        array = realloc(array, (num_elts + 1) * sizeof(char *)); // allocate space in the array
                        array[num_elts] = calloc(current_length + 1, sizeof(char)); // allocate space for the string
                        memcpy(array[num_elts++], str + consumed, (due_to_end == 0 ? current_length - 1 : current_length)); // copy the string to the current array offset's allocated memory, and remove 1 character (slash) if this is not the end of the string

                        consumed += current_length; // add what we consumed right now
                        current_length = 0; // reset current_length
                }
        }

        for (int i = 0; i < num_elts; i++) { // loop through all the elements for overview
                printf("%s\n", array[i]);
        }

}

Yes, the approach that you specify in your question seems good, in principle.是的,原则上,您在问题中指定的方法似乎不错。 However, I see the following problem:但是,我看到以下问题:

Using strcpy will require a null-terminated source string.使用strcpy将需要一个以 null 结尾的源字符串。 This means if you want to use strcpy , you will have to overwrite the / with a null character.这意味着如果你想使用strcpy ,你必须用 null 字符覆盖/ If you don't want to have to modify the source string by writing null characters into it, then an alternative would be to use the function memcpy instead of strcpy .如果您不想通过在其中写入 null 字符来修改源字符串,那么另一种方法是使用 function memcpy而不是strcpy That way, you can specify the exact number of characters to copy and you don't require the source string to have a null terminating character.这样,您可以指定要复制的确切字符数,并且不需要源字符串具有 null 终止字符。 However, this also means that you will somehow have to count the number of characters to copy.但是,这也意味着您必须以某种方式计算要复制的字符数。

On the other hand, instead of using strcpy or memcpy , you could simply copy one character at a time from str into arr[0] , until you encounter the next letter, and then copy one character at a time from str into arr[1] , and so on.另一方面,您可以不使用strcpymemcpy ,而是一次将一个字符从str复制到arr[0] ,直到遇到下一个字母,然后一次将一个字符从str复制到arr[1]等。 That solution may be simpler.该解决方案可能更简单。

In accordance with the community guidelines for homework questions , I will not provide a full solution to your problem at this time.根据家庭作业问题的社区指南,我目前不会为您的问题提供完整的解决方案。

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

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