4)替换空格
題目:https://www.2cto.com/article/201603/493415.html
請實現一個函數,把字符串中的每個空格替換成"%20"。例如輸入“We are happy.”,則輸出“We%20are%20happy.”。
思路 :
該題在書上主要需要借助指針的思路,不過Java沒有指針,但是Java字符串也有相應的API方法,可以指向字符串中的某一個位置,charAt();等,
主要思路,先遍歷數組有幾個空格,然后就能知道新字符串的長度為(原字符串str的長度+空格數*2)比如題目中的,str.length()=14,空格數為2,因此新字符串長度為18,設置兩個下標,一個下標指向原字符串的尾部,另一個下標指向新字符串的尾部,然后舊下標向前移動,將原子符串下標所指向的字符轉移到新字符串的下標位置,直到遇到空格,遇到空格便將%20賦值給新下標。直到遍歷結束。
代碼實現:
/**** @Description 替換空格** @author hsk*/// 題目:請實現一個函數,把字符串中的每個空格替換成"%20"。例如輸入“We are happy.”, // 則輸出“We%20are%20happy.”。public class ReplaceSpaces {/*** 實現空格的替換*/public String replaceSpace(StringBuffer str) {if (str == null) {System.out.println("輸入錯誤!");return null;}int length = str.length();int indexOfOriginal = length-1;for (int i = 0; i < str.length(); i++) {if (str.charAt(i) == ' ')length += 2;}str.setLength(length);int indexOfNew = length-1;while (indexOfNew > indexOfOriginal) {if (str.charAt(indexOfOriginal) != ' ') {str.setCharAt(indexOfNew--, str.charAt(indexOfOriginal));} else {str.setCharAt(indexOfNew--, '0');str.setCharAt(indexOfNew--, '2');str.setCharAt(indexOfNew--, '%');}indexOfOriginal--;}return str.toString();}// ==================================測試代碼==================================/*** 輸入為null*/public void test1() {System.out.print("Test1:");StringBuffer sBuffer = null;String s = replaceSpace(sBuffer);System.out.println(s);}/*** 輸入為空字符串*/public void test2() {System.out.print("Test2:");StringBuffer sBuffer = new StringBuffer("");String s = replaceSpace(sBuffer);System.out.println(s);}/*** 輸入字符串無空格*/public void test3() {System.out.print("Test3:");StringBuffer sBuffer = new StringBuffer("abc");String s = replaceSpace(sBuffer);System.out.println(s);}/*** 輸入字符串為首尾空格,中間連續空格*/public void test4() {System.out.print("Test4:");StringBuffer sBuffer = new StringBuffer(" a b c ");String s = replaceSpace(sBuffer);System.out.println(s);}public static void main(String[] args) {ReplaceSpaces rs = new ReplaceSpaces();rs.test1();rs.test2();rs.test3();rs.test4();} }?
?
總結
- 上一篇: 【Shell】 sed/tr替换换行符
- 下一篇: CS专业术语