URL化。编写一种方法,将字符串中的空格全部替换为%20
。假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的“真实”长度。(注:用Java
实现的话,请使用字符数组实现,以便直接在数组上操作。)
示例1:
输入:"Mr John Smith ", 13 输出:"Mr%20John%20Smith"
示例2:
输入:" ", 5 输出:"%20%20%20%20%20"
提示:
class Solution { public String replaceSpaces(String S, int length) { return S.substring(0, length).replaceAll(" ", "%20"); } }
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
。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
。原文:https://www.cnblogs.com/WLCYSYS/p/13372866.html