21xrx.com
2025-04-19 04:03:21 Saturday
文章检索 我的文章 写文章
如何用C语言对字符串进行字典排序
2023-06-18 14:14:35 深夜i     61     0
- C语言 - 字符串 - 字典排序 - strcmp函数 - 排序算法

在开发过程中,对字符串进行排序是一个常见的操作。本文将介绍如何使用C语言来对字符串进行字典排序。在C语言中,有很多库函数可以用来处理字符串,例如strcmp函数,它可以比较两个字符串的大小。下面是按字典顺序排序的字符串示例代码:

#include 
#include 
#define MAX 10
void Sort(char arr[][MAX], int n);
int main() {
  char str[][MAX] = "how";
  int n = 6;
  Sort(str, n);
  for(int i = 0; i < n; i++) {
    printf("%s\n", str[i]);
  }
  return 0;
}
void Sort(char arr[][MAX], int n) {
  int i, j;
  char temp[MAX];
  for(i = 0; i < n-1; i++) {
    for(j = i+1; j < n; j++) {
      if(strcmp(arr[i], arr[j]) > 0) {
        strcpy(temp, arr[i]);
        strcpy(arr[i], arr[j]);
        strcpy(arr[j], temp);
      }
    }
  }
}

在代码中,我们定义了一个字符串数组str,大小为n,然后我们使用Sort函数对其进行排序。Sort函数中使用了strcmp函数对两个字符串进行比较,如果第一个字符串比第二个字符串大,则交换它们的位置。最后,我们用for循环打印排序后的字符串。该程序的输出结果如下:

are
doing
hello
how
world
you

关键词:

- C语言

- 字符串

- 字典排序

- strcmp函数

- 排序算法

  
  

评论区