gpt4 book ai didi

c - C中句子中的单词按字母顺序排列?

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:59 25 4
gpt4 key购买 nike

我正在尝试将句子中的单词按字母顺序排列。它必须能够区分大写字母和小写字母,但我很难让它只区分小写字母。

如果我一次输入一个单词,它会按字母顺序排列,但一旦我输入多个单词,它就会表现得很奇怪。如果我输入“我需要帮助”,我希望收到“i deen ehlp”;相反,我收到 "i dnee ehlp"

这是我的代码:

#include <stdio.h>
#include <string.h>

int main (void)
{
int i, j, k, l=0, m=0, s=0, N=100;

printf("input a sentence with no more than 100 characters \n");
char sentence[N];
scanf("%[^\n]s", sentence);
int slength=strlen(sentence);

printf("Sentence before sorting - %s \n", sentence);
/*capital string keeps track of position of capital letters*/
int capital[slength];

for (i = 0; i < slength-1; i++)
{
for (j = i+1; j < slength; j++)
{
/*make uppercase letters lowercase */
if (sentence[j-1] <=90 && sentence[j-1]>64)
{
capital[l]=i;
sentence[i]=sentence[i]+32;
}
/* skip to next word if a space is detected */
if(sentence[j]==' ')
{
i=j+1;
j=j+2;
}
/*alphabetize loop*/
if (sentence[i] > sentence[j])
{
k = sentence[i];
sentence[i] = sentence[j];
sentence[j] = k;
}
}
}

printf("Sentence after sorting - %s \n", sentence);
return 0;
}

最佳答案

这是一个非常简单的解决方案。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int letter_sort(const void* a, const void* b)
{
return tolower(*(const char*)a) - tolower(*(const char*)b);
}

char* sentence_sort(char* s)
{
char _[strlen(s)+1];
strcpy(_,s);

for(char* w = strtok(_, " ."); w; w = strtok(NULL, " ."))
{
qsort(w, strlen(w), !!w, letter_sort);
memcpy(s+(w-_), w, strlen(w));
}
return(s);
}


int main(void) {
char sent[101];

printf("Input a sentence with no more than 100 characters \n");
scanf("%[^\n]", sent);

printf("Sentence before sorting: %s\n", sent);
printf("Sentence after sorting: %s\n", sentence_sort(sent));

return 0;
}

输出

Success #stdin #stdout 0s 9424KB
Input a sentence with no more than 100 characters
Sentence before sorting: The quick Brown fox Jumped over the Lazy Dogs.
Sentence after sorting: ehT cikqu Bnorw fox deJmpu eorv eht aLyz Dgos.

关于c - C中句子中的单词按字母顺序排列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54026145/

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