在这个问题中,我们得到了一个字符串数组。我们的任务是创建一个ac程序来对名称或字符串数组进行排序。该程序将按字母升序对输入中给出的所有名称进行排序。
让我们举个例子来了解这个问题,
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("\nGiven array of names: \t");
for (int i = 0; i < n; i++) printf("%s \t", arr[i]);
qsort(arr, n, sizeof(const char*), comparator);
printf("\nSorted 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