常見物件-把字串的首字母轉大寫其他轉小寫

ZHOU_VIP發表於2017-05-09

package cn.itcast_05;

/*
 * 需求:把一個字串的首字母轉成大寫,其餘為小寫。(只考慮英文大小寫字母字元)
 * 舉例:
 * 		helloWORLD
 * 結果:
 * 		Helloworld
 * 
 * 分析:
 * 		A:先獲取第一個字元
 * 		B:獲取除了第一個字元以外的字元
 * 		C:把A轉成大寫
 * 		D:把B轉成小寫
 * 		E:C拼接D
 */
public class StringTest {
	
	public static void main(String[] args) {
		// 定義一個字串
		String s = "helloWORLD";

		// 先獲取第一個字元
		String s1 = s.substring(0, 1);
		// 獲取除了第一個字元以外的字元
		String s2 = s.substring(1);
		// 把A轉成大寫
		String s3 = s1.toUpperCase();
		// 把B轉成小寫
		String s4 = s2.toLowerCase();
		// C拼接D
		String s5 = s3.concat(s4);
		System.out.println(s5);

		// 優化後的程式碼
		// 鏈式程式設計
		String result = s.substring(0, 1).toUpperCase().concat(s.substring(1).toLowerCase());
		System.out.println(result);
		
	}
}


相關文章