1. 程式人生 > 實用技巧 >面試題 01.03. URL化

面試題 01.03. URL化

URL化。編寫一種方法,將字串中的空格全部替換為%20。假定該字串尾部有足夠的空間存放新增字元,並且知道字串的“真實”長度。(注:用Java實現的話,請使用字元陣列實現,以便直接在陣列上操作。)

示例1:

 輸入:"Mr John Smith    ", 13
 輸出:"Mr%20John%20Smith"

示例2:

 輸入:"               ", 5
 輸出:"%20%20%20%20%20"

提示:

  1. 字串長度在[0, 500000]範圍內
  2. https://leetcode-cn.com/problems/string-to-url-lcci/
  3. https://www.cnblogs.com/WLCYSYS/p/13372866.html
class Solution {
    public String replaceSpaces(String S, int length) {
        return S.substring(0, length).replaceAll(" ", "%20");

    }
}

substring

public String substring(intbeginIndex,
                        intendIndex)
返回一個新字串,它是此字串的一個子字串。該子字串從指定的 beginIndex 處開始,直到索引 endIndex - 1 處的字元。因此,該子字串的長度為 endIndex-beginIndex

示例:

 "hamburger".substring(4, 8) returns "urge"
 "smiles".substring(1, 5) returns "mile"
 

引數:
beginIndex - 起始索引(包括)。
endIndex - 結束索引(不包括)。
返回:
指定的子字串。
丟擲:
IndexOutOfBoundsException - 如果 beginIndex 為負,或 endIndex 大於此 String 物件的長度,或 beginIndex 大於 endIndex

replace

public String replace(charoldChar,
                      charnewChar)
返回一個新的字串,它是通過用 newChar 替換此字串中出現的所有 oldChar 得到的。

如果 oldChar 在此 String 物件表示的字元序列中沒有出現,則返回對此 String 物件的引用。否則,建立一個新的 String 物件,它所表示的字元序列除了所有的 oldChar 都被替換為 newChar 之外,與此 String 物件表示的字元序列相同。

示例:

"mesquite in your cellar".replace('e', 'o')
         returns "mosquito in your collar"
 "the war of baronets".replace('r', 'y')
         returns "the way of bayonets"
 "sparring with a purple porpoise".replace('p', 't')
         returns "starring with a turtle tortoise"
 "JonL".replace('q', 'x') returns "JonL" (no change)
 

引數:
oldChar - 原字元。
newChar - 新字元。
返回:
一個從此字串派生的字串,它將此字串中的所有 oldChar 替代為 newChar