面试题 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(int beginIndex,
                        int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。该子字符串从指定的 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(char oldChar,
                      char newChar)
返回一个新的字符串,它是通过用 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

猜你喜欢

转载自www.cnblogs.com/WLCYSYS/p/13372866.html