c - 在 C 中对字符串文字进行排序
问题描述
假设我有一个在运行时提供的字符串文字:
const char *example_message
我想在运行时对字符串文字中的字符进行排序。
我该怎么做?
我尝试将文字复制到一个数组中,但这不起作用,因为它的大小在编译时是未知的。
我无法就地编辑字符串文字,因为它们是不可变的。
有任何想法吗?
解决方案
因为给定的字符指针是常量。所以它是不可变的。
因此,我可以动态或静态地创建一个临时字符数组并复制其中的值。qsort()
c
然后使用库函数对临时数组进行排序。
这是用于动态或静态创建临时字符数组的代码片段。
const char *str = "AZBCD";
int n = strlen(str);
char temp[n + 1];
strcpy(temp, str);
或者
const char *str = "AZBCD";
int n = strlen(str);
char *temp = (char*)malloc(sizeof(char) * n);
strcpy(temp, str);
这是结论性代码。
#include<stdio.h>
#include <stdlib.h>
int compare(const void * a, const void * b) {
int x = *( const unsigned char * )a;
int y = *( const unsigned char * )b;
/*
For ascending order & descending order.
Manipulate the below code and get your desire results.
1) x < y
a) if we return 1 then the string will sort descending order.
2) x > y
a) if we return 1 then the string will sort ascending order.
Vice versa is also possible.
*/
if(x > y) return 1;
return 0;
}
int main(void)
{
const char *str = "AZBCD";
int n = strlen(str);
printf("%s\n", str);
char temp[n + 1];
strcpy(temp, str);
qsort(temp, n, sizeof(char), compare);
printf("%s\n", temp);
return 0;
}
推荐阅读
- r - R purrr map2 更改列名 - 列名中的间距问题
- php-curl - 当 json 数据通过变量传递时,CURL 没有返回正确的响应
- c# - 在 IIS 上执行进程会使 RAM 快速上升
- windows - 适用于 Office 2016 的 Microsoft Office 文档映像 (MODI)
- postgresql - Azure DevOps CI 中 Azure 服务集成的自动化集成测试
- ios - 如何使用 GET API 请求在 AWS Cloud Search 中执行部分字符串搜索
- java - 未能执行目标 maven-compiler-plugin 3.8.0 - org/codehaus/plexus/compiler/manager/NoSuchCompilerException
- atom-editor - Atom Snippets - 得到保存但未列出且不起作用
- bash - bash: while - 一段时间后停止
- xamarin.forms - 如何在用户按下 Xamarin Forms 条目上的“返回”之前保持软键盘开启