提示:文章
文章目录
前言
前期疑问:
本文目标:
一、背景
最近
二、HJ26 字符串排序
2.1 代码
2.1.1 第一版
\#include <stdio.h>
\#include <stdlib.h>
int compar(void* a, void* b) {
return *(int*)a - *(int*)b;
}
int main() {
int array[10] = {24, 3, 4, 6, 8, 3, 7, 2, 5, 9};
qsort(array, 10, sizeof(int), compar);
for (int i = 0; i < 10; i++) {
//printf("%d ", array[i]);
}
char str[1001] = {'\0'};
while (gets(str) != NULL) { // 注意 while 处理多个 case
// 64 位输出请用 printf("%lld") to
//printf("%s\n", str);
int len = strlen(str);
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if ( (str[i] < 'a' && str[i] > 'z') && (str[i] < 'A' && str[i] > 'Z') ) {
break;
} else if ( (str[j] < 'a' && str[j] > 'z') && (str[j] < 'A' && str[j] > 'Z') ) {
break;
} else {
if (abs(str[i] - str[j]) == 32) {
continue;
} else if ( (str[i] >= 'a' && str[i] <= 'z') && (str[j] >= 'a' &&
str[j] <= 'z') ) {
if (str[i] > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
} else if ( (str[i] >= 'A' && str[i] <= 'Z') && (str[j] >= 'A' &&
str[j] <= 'Z') ) {
if (str[i] > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
} else if ( (str[i] >= 'a' && str[i] <= 'z') && (str[j] >= 'A' &&
str[j] <= 'Z') ) {
if (str[i] - 32 > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
} else if ( (str[i] >= 'A' && str[i] <= 'Z') && (str[j] >= 'a' &&
str[j] <= 'z') ) {
if (str[i] + 32 > str[j]) {
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
}
}
printf("%s\n", str);
}
return 0;
}
2.1.2 第二版
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
#include "stdbool.h"
bool isNeedExchange(char a, char b)
{
if( (!isalpha(a)) || (!isalpha(b)) )
{
return false;
}
if(tolower(a) - tolower(b) < 0)
{
return false;
}
return true;
}
int main() {
char str[1001] = {'\0'};
while (fgets(str, 1001, stdin) != NULL) { // 注意 while 处理多个 case
// 64 位输出请用 printf("%lld") to
//printf("%s\n", str);
strtok(str, "\n");
int len = strlen(str);
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if(isNeedExchange(str[i], str[j]))
{
char temp = str[i];
str[i] = str[j];
str[j] = temp;
}
}
}
printf("%s\n", str);
}
return 0;
}
//打印信息
自测输入:A Famous Saying: Much Ado About Nothing (2012/8).
预期输出:A aaAAbc dFgghh: iimM nNn oooos Sttuuuy (2012/8).
实际输出:A AaaAbc dFgghh: iiMm nNn ooooS sttuuuy (2012/8).
第二版代码虽然简化了代码,但是还是不对的。
至此,可能是我的算法不对。需要换算法。
2.1.3 第三版
只能说用对算法很简单
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include "string.h"
int main() {
char str[1001] = {'\0'};
char dstStr[1001] = {'\0'};
int dstStrIndex = 0;
while (fgets(str, 1001, stdin) != NULL) { // 注意 while 处理多个 case
// 64 位输出请用 printf("%lld") to
//printf("%s\n", str);
strtok(str, "\n");
int len = strlen(str);
for (int i = 0; i < 26; i++) {
for (int j = 0; j < len; j++) {
if(str[j] - 'a' == i || str[j] - 'A' == i)
{
dstStr[dstStrIndex++] = str[j];
}
}
}
dstStrIndex = 0;
for(int i = 0; i < len; i++)
{
if(isalpha(str[i]))
{
str[i] = dstStr[dstStrIndex++];
}
}
printf("%s\n", str);
}
return 0;
}
上面的代码ac了
总结
未完待续