用c语言单词按字母排序
时间: 2024-03-13 10:17:08 浏览: 31
以下是一个简单的C语言程序,可以对输入的单词按字母顺序进行排序:
```c
#include <stdio.h>
#include <string.h>
int main() {
char word[100];
int i, j, n;
printf("Enter a word: ");
scanf("%s", word);
n = strlen(word);
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (word[i] > word[j]) {
char tmp = word[i];
word[i] = word[j];
word[j] = tmp;
}
}
}
printf("Sorted word: %s\n", word);
return 0;
}
```
该程序首先从用户输入中获取一个单词,然后使用嵌套的循环对该单词进行排序。在外部循环中,我们遍历单词中的每个字符(除了最后一个字符),而在内部循环中,我们比较当前字符与后面的所有字符,并在需要时交换它们的位置。最后,程序输出已排序的单词。
相关问题
c语言按字母顺序对单词排序
可以使用C语言中的qsort函数对单词进行排序,具体实现可以参考以下代码:
```c
#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 words[10][20];
int i, n;
printf("Enter number of words: ");
scanf("%d", &n);
printf("Enter %d words:\n", n);
for(i = 0; i < n; i++)
scanf("%s", words[i]);
qsort(words, n, sizeof(words[0]), cmp);
printf("\nIn lexicographical order: \n");
for(i = 0; i < n; i++)
printf("%s\n", words[i]);
return 0;
}
```
在这个代码中,我们使用了qsort函数进行排序,cmp函数用于比较两个字符串的大小。在主函数中,我们先输入需要排序的单词,然后使用qsort函数进行排序,最后输出排序后的结果。
用c语言写一个按照字母表排序的单词程序
你好,我可以回答这个问题。以下是一个用 C 语言编写的按字母表排序的单词程序的示例代码:
```
#include <stdio.h>
#include <string.h>
#define MAX_WORDS 100
#define MAX_WORD_LENGTH 50
int main() {
char words[MAX_WORDS][MAX_WORD_LENGTH];
int i, j, n;
printf("请输入单词的个数:");
scanf("%d", &n);
printf("请输入 %d 个单词:\n", n);
for (i = ; i < n; i++) {
scanf("%s", words[i]);
}
// 冒泡排序
for (i = ; i < n - 1; i++) {
for (j = ; j < n - i - 1; j++) {
if (strcmp(words[j], words[j + 1]) > ) {
char temp[MAX_WORD_LENGTH];
strcpy(temp, words[j]);
strcpy(words[j], words[j + 1]);
strcpy(words[j + 1], temp);
}
}
}
printf("按字母表排序后的单词为:\n");
for (i = ; i < n; i++) {
printf("%s\n", words[i]);
}
return ;
}
```
这个程序使用冒泡排序算法对输入的单词进行排序,最终输出按字母表排序后的单词列表。希望能对你有所帮助。