Lanqiao Cup String Conversion (Java)

Problem-solving ideas : First of all, this problem seems to have five functional sections to be implemented. In general, switch statements are used for branch control. In fact, only the last section is difficult, which is equivalent to converting the string to lowercase first, and then performing regularization. The expression rewrites the output.
Difficulty in solving the problem : the first two sections can directly call the string method for output, the third and fourth sections, you can get the result by simply nesting loops, the fifth section is actually very simple, follow the idea of ​​regular matching Shown in the program structure.

package 蓝桥杯;

import java.util.Scanner;

public class 字符串转换 {
    
    
	public static void main(String[] args) {
    
    
		Scanner in = new Scanner(System.in);
		
		int n = in.nextInt();
		String str = in.next();
		
		switch(n) {
    
    
			case 1:System.out.println(str.toUpperCase());break;
			case 2:System.out.println(str.toLowerCase());break;
			case 3:for(int i = str.length()-1;i >= 0;i--) System.out.print(str.charAt(i));break;
			case 4:fourDemo(str);break;
			case 5:fiveDemo(str);break;
		}
		
	}
	//第四功能版块
	static void fourDemo(String str){
    
    
		for(int i = 0;i < str.length();i++) {
    
    
			if('A' < str.charAt(i) && str.charAt(i) < 'Z')
				System.out.print((char)(str.charAt(i)+32));
			else
				System.out.print((char)(str.charAt(i)-32));;
		}
	}
	//第五功能版块
	static void fiveDemo(String str){
    
    
		str = str.toLowerCase();
		System.out.print(str.charAt(0));
		int add = 1;
		for(int i = 1;i < str.length();i++) {
    
    
			if(str.charAt(i)-str.charAt(i-1) == 1) {
    
    
				if(i == str.length()-1) {
    
    
					if(add >= 2)
						System.out.print("-"+str.charAt(i));
					else
						System.out.print(str.charAt(i));
				}
				add++;
			}
			else {
    
    
				if(add > 2) {
    
    
					System.out.print("-"+str.charAt(i-1)+str.charAt(i));
					add = 1;
				}
				else
					System.out.print(str.charAt(i));
			}
		}
		
	}
}

Guess you like

Origin blog.csdn.net/baldicoot_/article/details/104756486