编写函数,将一个字符串中的字符进行降
序排序,井将排序后的字符串转换成整数数组。在main函数中验证
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string str = "Hello, World!";
sort(str.begin(), str.end(), greater<char>()); // 对字符串中的字符进行降序排序
cout << "Sorted string: " << str << endl;
int arr[str.length()]; // 定义整数数组
for (int i = 0; i < str.length(); i++) {
arr[i] = (int)str[i]; // 将排序后的字符转换成整数并存入数组中
}
// 输出整数数组
cout << "Array: ";
for (int i = 0; i < str.length(); i++) {
cout << arr[i] << " ";
}
cout << endl;
return 0;
}
输出的结果为
仅供参考!
#include <stdio.h>
#include <string.h>
//降序排序
void bubS(char *s)
{
char tmp;
size_t n = strlen(s);
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (s[j] < s[j + 1])
{
tmp = s[j];
s[j] = s[j + 1];
s[j + 1] = tmp;
}
}
}
}
//转成整数数组
void sToDigArr(char *s, int *arr)
{
size_t n = strlen(s);
for (int i = 0; i < n; i++)
{
arr[i] = s[i];
}
}
int main(void)
{
//验证
char s[256];
int arr[256], n;
scanf("%255[^\n]s", s);
n = strlen(s);
//降序排序
bubS(s);
//输出降序后的数组
puts("");
puts(s);
//转成整数数组输出
sToDigArr(s, arr);
for (int i = 0; i < n; i++)
{
if (i % 10 == 0)
puts("");
printf("%d ", arr[i]);
}
puts("");
return 0;
}