gpt4 book ai didi

c - 按字母顺序对单词进行排序 C

转载 作者:行者123 更新时间:2023-12-05 01:32:41 26 4
gpt4 key购买 nike

所以我的练习是对一维字符数组中的单词进行排序。我的代码几乎可以正常工作,但它总是会跳过最后一个单词的最后一个字符。这是我的代码。我添加了一些注释以使其具有某种可读性。我知道这不是出色的代码,但我才刚刚开始编程。

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。如果有人能帮我做意大利面,我会很高兴。

最佳答案

问题在于您如何处理空字节与空间。在空格的情况下,当您复制字符串时,您实际上 空格上。但在空字节的情况下,您空字节之前。这会导致差一错误。您需要修改代码以避免对空格和空字节进行不同的处理:

for (j = i; tab[j] != '\0'; j++) {
//In the space case, you are on the space, but in the \0 case
//you were one before it.
//Changed this if statement so that you always copy the string
//when you're at the last character.
if (tab[j + 1] == ' ' || tab[j + 1] == '\0') {

//k is a length, but we're using it as an index
//so we will need to adjust by one
for (g = k; g > 0; g--) {
tmp[l] = tab[j - g + 1];
l++;
}
}
else
{
k++;
}
}

我通过在每个循环中显示 tab[j] 的值和 k 的值的打印语句来解决这个问题。通过打印语句或调试器观察程序执行通常是诊断此类问题的最佳方法。

关于c - 按字母顺序对单词进行排序 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60139171/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com