![](/img/trans.png)
[英]Convert array of objects with string property to an array of strings in c#
[英]Convert String into Array of Strings in C
我正在嘗試將一串按字母順序排序的單詞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"
...
我對 C 不是很熟練,所以我的方法是聲明:
char arr[26][100];
char curr_letter = "a";
然后遍歷字符串中的每個字符以查找“/”,然后是 char,= curr_letter。 然后將 substring strcpy 到正確的位置。
我不確定我的方法是否很好,更不用說如何正確實施了。 任何幫助將不勝感激!
所以我們基本上循環遍歷字符串,檢查是否找到了“拆分字符”,還檢查了沒有找到下一個字符“curr_letter”。
我們跟蹤消耗的長度,當前長度(用於 memcpy 稍后將當前字符串復制到數組中)。
當我們找到一個 position 可以將當前字符串添加到數組中時,我們分配空間並將字符串復制到它作為數組中的下一個元素。 我們還將 current_length 添加到消費中,並且 current_length 被重置。
我們使用due_to_end
來確定當前字符串中是否有/
,並相應地刪除它。
嘗試:
#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]);
}
}
是的,原則上,您在問題中指定的方法似乎不錯。 但是,我看到以下問題:
使用strcpy
將需要一個以 null 結尾的源字符串。 這意味着如果你想使用strcpy
,你必須用 null 字符覆蓋/
。 如果您不想通過在其中寫入 null 字符來修改源字符串,那么另一種方法是使用 function memcpy
而不是strcpy
。 這樣,您可以指定要復制的確切字符數,並且不需要源字符串具有 null 終止字符。 但是,這也意味着您必須以某種方式計算要復制的字符數。
另一方面,您可以不使用strcpy
或memcpy
,而是一次將一個字符從str
復制到arr[0]
,直到遇到下一個字母,然后一次將一個字符從str
復制到arr[1]
等。 該解決方案可能更簡單。
根據家庭作業問題的社區指南,我目前不會為您的問題提供完整的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.