日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

4)替换空格

發布時間:2024/3/13 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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();} }

?



?

總結

以上是生活随笔為你收集整理的4)替换空格的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。