劍指Offer(java+第四題,替換空格)
阿新 • • 發佈:2018-11-26
思路:從後往前複製,陣列長度會增加,或使用StringBuilder、StringBuffer類
程式碼:
public class Offer_04 { public String replaceSpace(String str){ if(str == null||str.length()<=0)//str == null判斷字串是個null指標,str.length()<=0判斷字串是空字串 return null; StringBuilder sb = new StringBuilder(); for(int i = 0;i<str.length();i++){ if(String.valueOf(str.charAt(i)).equals(" ")){//String.valueOf():Returns the string representation of the char argument. sb.append("%20"); }else{ sb.append(str.charAt(i)); } } return String.valueOf(sb); } public static void main(String[] args) { Offer_04 of4 = new Offer_04(); //測試用例 //1,輸入的字串中包含空格(空格位於字串的最前面,空格位於字串的最後面,空格位於字串的中間,字串中有連續多個空格)。 String str1 = " We are happy."; System.out.println(of4.replaceSpace(str1)); String str2 = "We are happy. "; System.out.println(of4.replaceSpace(str2)); String str3 = "We are happy."; System.out.println(of4.replaceSpace(str3)); //2,輸入的字串中沒有空格 String str4 = "Wearehappy."; System.out.println(of4.replaceSpace(str4)); //特殊輸入測試(字串是個null指標 、字串是個空字串、字串只有一個空格字元、字串只有連續多個空格)。 String str5 = null; System.out.println(of4.replaceSpace(str5)); String str6 = "";//""表示空字串 System.out.println(of4.replaceSpace(str6)); String str7 = " ";//" "表示一個空格字元 System.out.println(of4.replaceSpace(str7)); String str8 = " ";//" "表示3個空格字元 System.out.println(of4.replaceSpace(str8)); } } /** * StringBuilder a = new StringBuilder("we are happy."); * String b = " " + a;//將StringBuilder型別轉換成String型別 * StringBuilder a = new StringBuilder(a);//將String型別轉換為StringBuilder型別 * */
輸出結果: