Java日记之正则表达式将多个空格换为一个

/**
 * 	给定输入的字符串,将字符串中的单词顺序颠倒,但要保持单词的字符顺序。例如:给定
	input=“changchun university of science and technology”,
	输出output=“technology and science of university changchun”。
	解答过程中,要注意对特殊情况的处理,例如,输入为“ ”,即多个空格时,要输出“ ”,即一个空格
 * 
 * */
 static Scanner scan = new Scanner(System.in);
	static String input = "";
	static String output = "";
	
	public static void main(String[] args) {
		input = scan.nextLine();
		String tmp="";
		for(int i=0;i<input.length();i++) {
			//遍历字符串,连续" "多个时,replace掉,最后转置
			
			if(input.charAt(i)==' ' && input.charAt(i)+1 !=' ') {
				//只有一个' '时
				//不操作
			}else {
				tmp = input.replaceAll("[' ']+"," "); 
				//正则表达式,超过一个空格都变成一个空格
			}
		}
		
		//根据空格拆分成N个数组,再拼接
		String[] arr = tmp.split(" ");
		
		for(int i=arr.length-1;i>=0;i--) {
			output+=arr[i];
			
			output+= ( i==0 ? "" : " "); //去最后一个空格
		}
		System.out.println(output);
		
	}

猜你喜欢

转载自blog.csdn.net/qq_45596525/article/details/107764039