蓝桥杯 字符串变换

蓝桥杯 字符串变换

题目

相信经过这个学期的编程训练,大家对于字符串的操作已经掌握的相当熟练了。今天,徐老师想测试一下大家对于字符串操作的掌握情况。徐老师自己定义了1,2,3,4,5这5个参数分别指代不同的5种字符串操作,你需要根据传入的参数,按照徐老师的规定,对输入字符串进行格式转化。

徐老师指定的操作如下:

  1. 表示全部转化为大写字母输出,如abC 变成 ABC
  2. 表示全部转换为小写字母输出,如abC变成abc
  3. 表示将字符串整个逆序输出,如 abc 变成 cba
  4. 表示将字符串中对应的大写字母转换为小写字母,而将其中的小写字母转化为大写字母输出,如 abC变成ABc
  5. 表示将全部转换为小写字母,并将其中所有的连续子串转换为对应的缩写形式输出,比如abcD 转换为a-d,其次,-至少代表1个字母,既如果是ab,则不需要转换为缩写形式。

输入格式

一共一行,分别是指代对应操作的数字和字符串,两者以空格分隔,字符串全部由英文字母组成。

输出格式

输出根据上述规则转换后对应的字符串。

输入样例

1
5 ABcdEE

输出样例

1
a-ee

数据规模和约定

输入字符串长度最长为200。

思路

一个switch()控制功能,1,2,3,4简单。5的话,全部转换为小写后,遍历字符串的字符,判断是否后边的字符-前面的字符=1,是的话,flag=true表示当前的字母是连续的,如果不是的话,flag=false并打印范围。直到遍历完。
这里隐藏了一个特殊条件:当扫描到最后一个字母时,连续模式还在继续,于是无法结束。比如aabcd,所以判断一下当遍历到最后一个字符时,如果flag=true就强制停止,并输出范围。

代码

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
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
String b = s.nextLine();
b = b.substring(1);
s.close();
switch (a) {
case 1:
System.out.println(b.toUpperCase());
break;
case 2:
System.out.println(b.toLowerCase());
break;
case 3:
System.out.println(new StringBuffer(b).reverse());
break;
case 4:
char[] c = b.toCharArray();
for(char w:c){
if(w>64&&w<91){
w+=32;
}else {
w-=32;
}
System.out.print(w);
}
System.out.println();
break;
case 5:
b = b.toLowerCase();
char[] d = b.toCharArray();
char last = d[0];
Boolean isS = false;
for(int i = 0;i<d.length;i++){
if(i==d.length-1){
if(isS){
System.out.print('-');
if(d[d.length-1]-d[d.length-2]!=1){
System.out.print(last);
}
System.out.print(d[i]);
break;
}else {
System.out.print(d[i]);
}
}else if(d[i]-last==1){
isS = true;
}else if(isS){
System.out.print('-');
System.out.print(last);
System.out.print(d[i]);
isS = false;
}else {
System.out.print(d[i]);
}
last = d[i];
}
break;
}
}
}
文章作者: Shengyaqingfeng
文章链接: https://creazyboyone.github.io/lqb379/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Shengyaqingfeng's Blog