C 如何按字母顺序对字符串中的单词进行排序
按字母顺序排列字符串中的单词最简单的方法是什么? 我编写了以下代码,但它不适用于较小的单词,而且它还打印了许多垃圾值。你能告诉我为什么吗C 如何按字母顺序对字符串中的单词进行排序,c,alphabetical-sort,C,Alphabetical Sort,按字母顺序排列字符串中的单词最简单的方法是什么? 我编写了以下代码,但它不适用于较小的单词,而且它还打印了许多垃圾值。你能告诉我为什么吗 #include<stdio.h> #include<string.h> void main() { int i=0,j=0,k=0,l=0,n,wmax=0,tem; char text[80]; char sort[80]; char temp[20]; struct word // a st
#include<stdio.h>
#include<string.h>
void main()
{
int i=0,j=0,k=0,l=0,n,wmax=0,tem;
char text[80];
char sort[80];
char temp[20];
struct word // a structure to contain a single word and it's length
{
char text[10];
int length;
}
word[20];
printf("Enter a line of text");
gets(text);
while(text[j]!='\0')
{
if(text[j]==' ')
wmax++;j++;
};
wmax=j;
for(i=0;i<j;i++)
{
if(text[i]==' ')
{
word[k].text[l]='\0';
k++;
l=0;
continue;
}
word[k].text[l]=text[i];
word[k].length=l;
l++;
}
for(n=0;n<wmax;n++){
for(i=0;i<wmax;i++)
{
for(j=0;j<word[i].length;j++)
{
if(word[i].text[j]>word[i+1].text[j])
{
strcpy(temp,word[i].text);
strcpy(word[i].text,word[i+1].text);
strcpy(word[i+1].text,temp);
}
if(word[i].text[j]==word[i+1].text[j])
continue;
if(word[i].text[j]<word[i+1].text[j]);
break;
}
}
}
for(j=0;j<wmax;j++){
puts(word[j].text);
}
#包括
#包括
void main()
{
int i=0,j=0,k=0,l=0,n,wmax=0,tem;
字符文本[80];
字符排序[80];
煤焦温度[20];
struct word//包含单个单词及其长度的结构
{
字符文本[10];
整数长度;
}
字[20];
printf(“输入一行文本”);
获取(文本);
而(文本[j]!='\0')
{
如果(文本[j]='')
wmax++;j++;
};
wmax=j;
对于(i=0;i#包括
#包括
#包括
int cmp(常数无效*a,常数无效*b){
返回strcmp(*(字符**)a、*(字符**)b);
}
int main(){
字符文本[80];
字符*字[40];
字符*字;
int wmax=0,i;
printf(“输入一行文本:”);
scanf(“%79[^\n]”,文本);
for(word=strtok(text,“”);word;word=strtok(NULL,“”){
words[wmax++]=word;
}
qsort(单词、wmax、sizeof(*单词)、cmp);
对于(i=0;i1)进行更好的识别2)尝试将字符串拆分为单词,然后对嵌套的单词进行排序没有缩进的单词会让我头晕。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b){
return strcmp(*(char**)a, *(char**)b);
}
int main(){
char text[80];
char *words[40];
char *word;
int wmax=0, i;
printf("Enter a line of text :");
scanf("%79[^\n]", text);
for(word = strtok(text, " "); word ; word = strtok(NULL, " ")){
words[wmax++] = word;
}
qsort(words, wmax, sizeof(*words), cmp);
for(i=0;i<wmax;++i)
printf("%s\n", words[i]);
return 0;
}