【小试牛刀】字符串操作之语序颠倒/大小写互转

1、编程实现将字符串先进行大小写互转,再进行字符串反转。

输入:AuJKtHyKy

输出:YkYhTkjUa

代码实现:

  1 package com.fhcq.reverseAndChange;
  2 
  3 /**
  4  * 编程实现将字符串先进行大小写互转,再进行字符串反转。
  5  * 输入:AuJKtHyKy
  6  * 输出:YkYhTkjUa
  7  */
  8 public class ReverseAndChange {
  9 
 10 	public static void main(String[] args) {
 11 		String s = "AuJKtHyKy";
 12 		reverseAndChange(s);
 13 	}
 14 
 15 	public static void reverseAndChange(String str) {
 16 
 17 		char[] ch = str.toCharArray();// 字符串转换为字符数组
 18 		StringBuffer sb = new StringBuffer();
 19 		for (int i = 0; i < ch.length; i++) {
 20 			if (ch[i] >= 'a' && ch[i] <= 'z') {
 21 				sb.append(String.valueOf(ch[i]).toUpperCase());
 22 			} else if (ch[i] >= 'A' && ch[i] <= 'Z') {
 23 				sb.append(String.valueOf(ch[i]).toLowerCase());
 24 			}
 25 		}
 26 		String result = sb.reverse().toString();// 将sb逆序,并转换为字符串形式
 27 		System.out.println(result);
 28 	}
 29 
 30 }
 31 


2、请编写一段代码,将下面的句子的语序颠倒:
“Long long ago , there lived a king”。
(提示:即把上述句子变成“king a lived there , ago long Long”)。

实现方式一:

  1 package com.fhcq.sentenceReverse;
  2 
  3 /**
  4  * 请编写一段代码,将下面的句子的语序颠倒:
  5  * “Long long ago , there lived a king”。
  6  * (提示:即把上述句子变成“king a lived there , ago long Long”)。
  7  */
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 public class SentenceReverse {
 12 	public static void main(String[] args) {
 13 
 14 		String str = "Long long ago , there lived a king";
 15 
 16 		List<String> list = new ArrayList<String>();
 17 
 18 		StringBuffer buffer = new StringBuffer(str).reverse();
 19 		String[] strings = buffer.toString().split(" ");
 20 
 21 		for (String string : strings) {
 22 			StringBuilder builder = new StringBuilder(string).reverse();
 23 			list.add(builder.toString());
 24 		}
 25 
 26 		for (int i = 0; i < list.size(); i++) {
 27 			System.out.print(list.get(i) + " ");
 28 		}
 29 	}
 30 }

实现方式二:

  1 package com.fhcq.sentenceReverse;
  2 
  3 /**
  4  * 请编写一段代码,将下面的句子的语序颠倒:
  5  * “Long long ago , there lived a king”。
  6  * (提示:即把上述句子变成“king a lived there , ago long Long”)。
  7  */
  8 import java.util.ArrayList;
  9 import java.util.List;
 10 
 11 public class SentenceReverse {
 12 	public static void main(String[] args) {
 13 
 14 		String str = "Long long ago , there lived a king";
 15 
 16 		List<String> list = new ArrayList<String>();
 17 
 18 		String[] strings = str.split(" ");
 19 
 20 		for (int i = strings.length - 1; i >= 0; i--) {
 21 			list.add(strings[i]);
 22 		}
 23 		for (int j = 0; j < list.size(); j++) {
 24 			System.out.print(list.get(j) + " ");
 25 		}
 26 
 27 	}
 28 }
posted @ 2017-11-09 10:43  长情白月光  阅读(664)  评论(0编辑  收藏  举报