【发布时间】:2020-02-09 17:13:35
【问题描述】:
所以我的练习是在一维字符数组中对单词进行排序。我的代码几乎可以工作,但它总是跳过最后一个单词的最后一个字符。这是我的代码。我添加了一些 cmets 以使其具有某种可读性。我知道这不是出色的代码,但我才刚刚开始编程。
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。如果有人能帮我做这个意大利面,我会很高兴的。
【问题讨论】:
-
您的排序函数说它将返回一个 int。它没有。
-
“但我才刚开始编程。”、“如果有人可以帮助我”和@Retired Ninja 暗示你犯了一个常见的学习错误:不是首先使用自动化作为编译器并出现警告也没有完全启用。节省时间,大量时间,并完全启用编译器警告。在这里更快地反馈帖子。