C 程式對一組名字或字串進行排序
在這個問題中,我們給定一個字串陣列。我們的任務是建立一個 c 程式來對一組名字或字串進行排序。此程式將根據升序字母順序對輸入中給出的所有名字進行排序。
我們舉個例子來理解一下這個問題,
輸入
namesArray = ["Rishabh", "Jyoti", "Palak", "Akash"]
輸出
["Akash", "jyoti", "palak", "Rishabh"]
為了解決這個問題,我們將使用標準模板庫的 qsort() 函式,因為我們知道整數值的排序,這裡改變的是,我們考慮字串進行比較,而不是整數值。
因此,將更改在 qsort() 中使用的比較器,並且 strcmp() 將用於比較比較器中的字串。透過這種方式,我們可以對一組名字或字串進行排序。
C 程式對一組名字或字串進行排序
示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int comparator(const void* str1, const void* str2) {
if(strcmp(*(const char**)str1, *(const char**)str2) >= 0)
return 1;
else return 0;
}
int main() {
const char* arr[] = {"Rishabh", "Jyoti", "Palak", "Akash"};
int n = sizeof(arr) / sizeof(arr[0]);
printf("
Given array of names: \t");
for (int i = 0; i < n; i++) printf("%s \t", arr[i]);
qsort(arr, n, sizeof(const char*), comparator);
printf("
Sorted array of names: \t");
for (int i = 0; i < n; i++)
printf("%s \t", arr[i]);
return 0;
}輸出
Given array of names: Rishabh Jyoti Palak Akash Sorted array of names: Akash Jyoti Palak Rishabh
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP