字符串合并处理

字符串合并处理

题目

将输入的两个字符串合并。

对合并后的字符串进行排序,要求为:下标为奇数的字符和下标为偶数的字符分别从小到大排序。这里的下标意思是字符在字符串中的位置。

对排序后的字符串进行操作,如果字符为‘0’——‘9’或者‘A’——‘F’或者‘a’——‘f’,则对他们所代表的16进制的数进行BIT倒序的操作,并转换为相应的大写字符。如字符为‘4’,为0100b,则翻转后为0010b,也就是2。转换后的字符为‘2’; 如字符为‘7’,为0111b,则翻转后为1110b,也就是e。转换后的字符为大写‘E’。题目出处

举例:输入str1为”dec”,str2为”fab”,合并为“decfab”,分别对“dca”和“efb”进行排序,排序后为“abcedf”,转换后为“5D37BF”

思路

先合并,再分割,分别排序,再合并。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#pragma warning(disable : 4996) //get 和 scanf 都不安全,在此忽略危险
void ProcessString(char* str1, char* str2, char* strOutput); //处理函数
int comp(const void* a, const void* b); //用于qsort的辅助函数
int main(void)
{
char str1[1000];
char str2[1000];
char str3[2000];
while (scanf("%s %s",str1,str2)!=EOF)
{
ProcessString(str1, str2, str3);
}
return 0;
}
void ProcessString(char* str1, char* str2, char* strOutput)
{
strcat(str1, str2); //第一次合并
char temp1[1000];
char temp2[1000];
char temp[2001];
int i, j, k;
for (i = 0, j = 0, k = 0; i < strlen(str1); i++)
if ((i % 2) == 0)
temp1[j++] = str1[i]; //在temp1存储偶数位
else temp2[k++] = str1[i]; //在temp2存储奇数位
temp1[j] = '\0'; //添加'\0'
temp2[k] = '\0';

qsort(temp1, j, sizeof(char), comp); //快速排序函数
qsort(temp2, k, sizeof(char), comp); //快速排序函数
for (i = 0, j = 0, k = 0; i < strlen(str1); i++)
{
if ((i % 2) == 0)
temp[i] = temp1[j++];
else temp[i] = temp2[k++]; //合并字符串
}
temp[i] = '\0';
for (i = 0; i < strlen(temp); i++) //按要求修改字符串,可以用switch
{
if (isdigit(temp[i]))
{
if ((temp[i]) == '1')
{
temp[i] = '8'; continue;
}
if ((temp[i]) == '2')
{
temp[i] = '4'; continue;
}
if ((temp[i]) == '3')
{temp[i] = 'C'; continue;
}
if ((temp[i]) == '4')
{
temp[i] = '2'; continue;
}
if ((temp[i]) == '5')
{
temp[i] = 'A'; continue;
}
if ((temp[i]) == '7')
{
temp[i] = 'E'; continue;
}
if ((temp[i]) == '8')
{
temp[i] = '1'; continue;
}
}
if (isalpha(temp[i]))
if((temp[i]<='f'&&temp[i]>='a')|| (temp[i] <= 'F' && temp[i] >= 'A'))
{
temp[i] = toupper(temp[i]);
if ((temp[i]) == 'A')
{temp[i] = '5'; continue; }
if ((temp[i]) == 'B')
{temp[i] = 'D'; continue; }
if ((temp[i]) == 'C')
{temp[i] = '3'; continue; }
if ((temp[i]) == 'D')
{temp[i] = 'B'; continue; }
if ((temp[i]) == 'E')
{temp[i] = '7'; continue; }
}
}
puts(temp);

}
int comp(const void* a, const void* b)
{
const char* a1 = (const char*)a;
const char* b1 = (const char*)b;
return (strcmp(a1, b1)); //将字符按照先后顺序排序
}

反思

字符串处理时可以用switch进行选择(数量较少时),也可以再调用函数将16进制转化为二进制,倒序再转化回去(数量多时更好运用)。

打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2020 lsengard
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信