【发布时间】:2019-01-20 18:12:32
【问题描述】:
我的代码只返回按字母顺序排列的第一个字母。例如。如果输入词是“coderbyte”,我想要的返回结果应该是“bcdeeorty”。但是,我的程序返回“bbbbbbbbb”。我花了几个小时试图弄清楚,我的代码对我来说似乎还可以,但显然不是。
#include <stdio.h>
#include <string.h>
void AlphabetSoup(char str[]) {
int first = str[0]; // code goes here
int index = 0;
int copy[8];
int current = copy[index];
int k = 0 ;
for (int i = 0; i < strlen(str); i++) {
if ( str[i] > str[i-1] ) {
copy[0] = str[i-1]; // first character
}
if(i == strlen(str) -1){
printf("%c", copy[0]); // printing the first character
index += 1; // incrementing the str[index]
}
}
while (k < strlen(str)){
for (int j = index; j < strlen(str); j++) {
if( str[j] > str[j-1] ) {
current = str[j-1];
}
if(j == strlen(str) - 1){
printf("%c", current);
index += 1;
}
}
k++;
}
}
int main() {
AlphabetSoup("coderbyte"); // bcdeeorty
}
【问题讨论】:
-
int copy[8]; int current = copy[index];copy未初始化。 -
你可以使用
qsort()。 -
您使用
copy可能未初始化,而str[i - 1]和i = 0您访问str的内存越界并且您的代码无法排序。 -
您的代码没有显示它应该完成的任务 - 比较 cmets
// arrange chars in array up to terminating NUL in ascending order与// code goes here。
标签: c algorithm alphabetical alphabetical-sort