我有一個程序,我寫了一個字符串,並根據出現的分隔符分隔每個單詞並將其添加到數組中。佔用多個分隔符的代碼不起作用
我已將其調整爲考慮'','。'要麼 '。'。現在的目標是調整多個分隔符一起出現(如「狗,走路」),並且仍然只添加該單詞。雖然我的程序運行正常,並且不打印額外的分隔符,但每次遇到其他分隔符時,它都會在輸出中包含一個空格而不是忽略它們。
int main(int argc, const char * argv[]) {
char *givenString = "USA,Canada,Mexico,Bermuda,Grenada,Belize";
int stringCharCount;
//get length of string to allocate enough memory for array
for (int i = 0; i < 1000; i++) {
if (givenString[i] == '\0') {
break;
}
else {
stringCharCount++;
}
}
// counting # of commas in the original string
int commaCount = 1;
for (int i = 0; i < stringCharCount; i++) {
if (givenString[i] == ',' || givenString[i] == '.' || givenString[i] == ' ') {
commaCount++;
}
}
//declare blank Array that is the length of commas (which is the number of elements in the original string)
//char *finalArray[commaCount];
int z = 0;
char *finalArray[commaCount] ;
char *wordFiller = malloc(stringCharCount);
int j = 0;
char current = ' ';
for (int i = 0; i <= stringCharCount; i++) {
if (((givenString[i] == ',' || givenString[i] == '\0' || givenString[i] == ',' || givenString[i] == ' ') && (current != (' ' | '.' | ',')))) {
finalArray[z] = wordFiller;
wordFiller = malloc(stringCharCount);
j=0;
z++;
current = givenString[i];
}
else {
wordFiller[j++] = givenString[i];
}
}
for (int i = 0; i < commaCount; i++) {
printf("%s\n", finalArray[i]);
}
return 0;
}
這個程序花了我幾個小時的時間聚集在一起(在經驗豐富的開發人員的幫助下),我不禁感到沮喪。我使用調試器來實現我的最佳能力,但絕對需要更多的經驗。
/////////
我回到墊和紙,那種重寫我的代碼。現在我試圖將分隔符存儲在數組中,並將該數組的元素與當前字符串值進行比較。如果它們是平等的,那麼我們遇到了一個新單詞,並將它添加到最終的字符串數組中。我正在努力弄清楚我將用於此目的的「for」循環的位置和內容。
char * original = "USA,Canada,Mexico,Bermuda,Grenada,Belize";
//creating two intialized variables to count the number of characters and elements to add to the array (so we can allocate enough mmemory)
int stringCharCount = 0;
//by setting elementCount to 1, we can account for the last word that comes after the last comma
int elementCount = 1;
//calculate value of stringCharCount and elementCount to allocate enough memory for temporary word storage and for final array
for (int i = 0; i < 1000; i++) {
if (original[i] == '\0') {
break;
}
else {
stringCharCount++;
if (original[i] == ',') {
elementCount++;
}
}
}
//account for the final element
elementCount = elementCount;
char *tempWord = malloc(stringCharCount);
char *finalArray[elementCount];
int a = 0;
int b = 0;
//int c = 0;
//char *delimiters[4] = {".", ",", " ", "\0"};
for (int i = 0; i <= stringCharCount; i++) {
if (original[i] == ',' || original[i] == '\0') {
finalArray[a] = tempWord;
tempWord = malloc(stringCharCount);
tempWord[b] = '\0';
b = 0;
a++;
}
else {
tempWord[b++] = original[i];
}
}
for (int i = 0; i < elementCount; i++) {
printf("%s\n", finalArray[i]);
}
return 0;
}
更好:'int stringCharCount = strlen(givenString);' – DrKoch
@karan,如果他們沒有對代碼的作用有一個基本的瞭解,那麼很難幫助有特殊問題的人。問題在於''wordFiller'所在的''for'永遠不會進入,因爲你的'current'變量是一個'',並且你有一個&&操作符,對於測試,它總是會返回爲false,並且永遠不要輸入該代碼塊。 – Jaques
也是:'wordFiller = malloc(stringCharCount);'會分配太少的字節。 – DrKoch