[英]Alphabetize words in sentence in C?
I am trying to take words in a sentence and alphabetize them each.我试图在一个句子中取单词并将它们按字母顺序排列。 it has to be able to differentiate between upper and lower case letters but i am having trouble getting it to do just lower case letters.
它必须能够区分大写和小写字母,但我很难让它只做小写字母。
If I input one word at a time it will alphabetize it but once I input multiple words it acts weird.如果我一次输入一个词,它会按字母顺序排列,但一旦我输入多个词,它就会表现得很奇怪。 If I input
"i need help"
, I expect to receive "i deen ehlp"
;如果我输入
"i need help"
,我希望收到"i deen ehlp"
; instead I receive "i dnee ehlp"
相反,我收到
"i dnee ehlp"
Here is my code:这是我的代码:
#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;
}
This is a very simple solution.这是一个非常简单的解决方案。
#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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.