我正在嘗試將按字母順序排序的單詞字串劃分為按字母順序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";
然后遍歷字串中的每個字符以查找“/”,然后是字符!= curr_letter,然后將該子字串strcpy到正確的位置。
我不確定我的方法是否很好,更不用說如何正確實施了。任何幫助將不勝感激!
uj5u.com熱心網友回復:
所以我們基本上回圈遍歷字串,并檢查是否找到了“拆分字符”,我們還檢查了是否沒有找到下一個字符“curr_letter”。
我們跟蹤消耗的長度,當前長度(用于 memcpy 稍后將當前字串復制到陣列中)。
當我們找到可以將當前字串添加到陣列的位置時,我們分配空間并將字串復制到它作為陣列中的下一個元素。我們還將 current_length 添加到消費中,并且 current_length 被重置。
我們due_to_end用來找出/當前字串中是否有 a,并相應地洗掉它。
嘗試:
#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]);
}
}
uj5u.com熱心網友回復:
是的,原則上,您在問題中指定的方法似乎不錯。但是,我看到以下問題:
使用strcpy將需要一個以 null 結尾的源字串。這意味著如果您想使用strcpy,則必須/用空字符覆寫 。如果您不想通過將空字符寫入源字串來修改源字串,那么另一種方法是使用該函式memcpy而不是strcpy. 這樣,您可以指定要復制的確切字符數,并且不需要源字串具有空終止字符。但是,這也意味著您必須以某種方式計算要復制的字符數。
另一方面,不使用strcpyor memcpy,您可以簡單地從strinto一次復制一個字符arr[0],直到遇到下一個字母,然后從strinto一次復制一個字符arr[1],依此類推。該解決方案可能更簡單。
根據家庭作業問題的社區指南,我目前不會為您的問題提供完整的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418865.html
標籤:
