日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

4)替换空格

發(fā)布時(shí)間:2024/3/13 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 4)替换空格 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

題目:https://www.2cto.com/article/201603/493415.html

請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù),把字符串中的每個(gè)空格替換成"%20"。例如輸入“We are happy.”,則輸出“We%20are%20happy.”。

思路 :

該題在書(shū)上主要需要借助指針的思路,不過(guò)Java沒(méi)有指針,但是Java字符串也有相應(yīng)的API方法,可以指向字符串中的某一個(gè)位置,charAt();等,

主要思路,先遍歷數(shù)組有幾個(gè)空格,然后就能知道新字符串的長(zhǎng)度為(原字符串str的長(zhǎng)度+空格數(shù)*2)比如題目中的,str.length()=14,空格數(shù)為2,因此新字符串長(zhǎng)度為18,設(shè)置兩個(gè)下標(biāo),一個(gè)下標(biāo)指向原字符串的尾部,另一個(gè)下標(biāo)指向新字符串的尾部,然后舊下標(biāo)向前移動(dòng),將原子符串下標(biāo)所指向的字符轉(zhuǎn)移到新字符串的下標(biāo)位置,直到遇到空格,遇到空格便將%20賦值給新下標(biāo)。直到遍歷結(jié)束。

代碼實(shí)現(xiàn):

/**** @Description 替換空格** @author hsk*/// 題目:請(qǐng)實(shí)現(xiàn)一個(gè)函數(shù),把字符串中的每個(gè)空格替換成"%20"。例如輸入“We are happy.”, // 則輸出“We%20are%20happy.”。public class ReplaceSpaces {/*** 實(shí)現(xiàn)空格的替換*/public String replaceSpace(StringBuffer str) {if (str == null) {System.out.println("輸入錯(cuò)誤!");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();}// ==================================測(cè)試代碼==================================/*** 輸入為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);}/*** 輸入字符串無(wú)空格*/public void test3() {System.out.print("Test3:");StringBuffer sBuffer = new StringBuffer("abc");String s = replaceSpace(sBuffer);System.out.println(s);}/*** 輸入字符串為首尾空格,中間連續(xù)空格*/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();} }

?



?

總結(jié)

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

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。