我的练习是对1D字符数组中的单词进行排序。 我的代码几乎可以工作,但它总是跳过最后一个单词的最后一个字符。 这是我的代码。 我添加了一些注释以使其有些可读性。 我知道这不是很好的代码,但我刚刚开始学习编程。
int main(void) {
char input[] = "If you are working on something that you really care about you dont have to be pushed The vision pulls you Steve Jobs";
sort_alphabetically(input);
printf("%s", input);
}
int sort_alphabetically(char tab[]) {
int j = 0, k = 0, i = 0, g = 0, f = 0, l = 0;
char tmp[1001];
char tmp2[501][1001];
while (tab[i] == ' ') // skipping leading whitespaces
i++;
for (j = i; tab[j] != '\0'; j++) {
if (tab[j] != ' ' && tab[j + 1] != '\0')
k++; // counting word length
else if (tab[j] == ' ' || tab[j + 1] == '\0' || tab[j + 1] == '\0') {
// copying word t0 2d array
for (g = k; g > 0; g--) {
tmp[l] = tab[j - g];
l++;
}
tmp[l] = 0;
strcpy(tmp2[f], tmp); // copying
f++; //words ++ in tmp2
k = 0;
l = 0;
tmp[0] = 0;
}
}
tab[0] = 0;
tmp[0] = 0;
for (j = 0; j < f; j++) {
for (i = 0; i < f - 1; i++) {
if (strcmp(tmp2[i], tmp2[i + 1]) > 0) { //sorting words in alphabeticall order
strcpy(tmp, tmp2[i]);
strcpy(tmp2[i], tmp2[i + 1]);
strcpy(tmp2[i + 1], tmp);
}
}
}
for (i = 0; i < f; i++) {
strcat(tab, tmp2[i]); // copying to tab
strcat(tab, " "); //adding spaces after each word
}
// removing whitespaces
for (i = 0; tab[i] == ' ' || tab[i] == '\t'; i++);
for (j = 0; tab[i]; i++) {
tab[j++] = tab[i];
}
tab[j] = '\0';
}
;
运行这段代码后,它会将最后一个单词(Jobs)中的
s
切掉。如果有人能帮我理清这个问题就太好了。