思路:從後往前複製,陣列長度會增加,或使用stringbuilder、stringbuffer 類
/**
* 解法一:使用stringbuffer
* * @param str 輸入字串
* @return 輸出結果
*/public
static string replaceblank1
(string str)
stringbuffer buffer =
newstringbuffer()
;for
(int i =
0; i < str.
length()
; i++
)else
}return string.
valueof
(buffer)
;}
/**
* 解法二:使用stringbuilder
* * @param str 輸入字串
* @return 輸出結果
*/public
static string replaceblank2
(string str)
stringbuilder sb =
newstringbuilder()
;for
(int i =
0; i < str.
length()
; i++
)else
}return string.
valueof
(sb)
;}
/**
* 解法三:使用string自帶的replaceall方法
* * @param str 輸入字串
* @return 輸出結果
*/public
static string replaceblank3
(string str)
return str.
replaceall
(" "
,"%20");
}
/**
* 解法四:字元陣列替換
* * @param str 輸入字串
* @return 輸出結果
*/public
static string replaceblank4
(string str)
int length = str.
length()
;char
array =
newchar
[length *3]
;int size =0;
for(
int i =
0; i < length; i++
)else
} string newstr =
newstring
(array,
0, size)
;return newstr;
}
/**
* 解法五:從後往前複製
* * @param str 輸入字串
* @return 輸出結果
*/public
static string replaceblank5
(string str)
int blanknum =0;
int length = str.
length()
;int newlength =0;
for(
int i =
0; i < length; i++)}
// 替換後的字串長度
newlength = length +
2* blanknum;
char
newchars =
newchar
[newlength]
;int index = newlength -1;
for(
int i = length -
1; i >=
0; i--
)else
}return
newstring
(newchars)
;}
/**
* 測試test5
* * 第5題
* 將乙個字串中的空格替換成"%20"
* * @author smallz
* @version 1.0
* @date 2020/3/28 18:03
*/public
class
test5
}
劍指Offer05 替換字串中的空格
劍指offer上面的分析 看到這個題目,我們首先應該想到的是原來乙個空格字元,替換之後變成 2 和 0這3個字元,因此字串會變長。如果是在原來的字串.上做替換,那麼就有可能覆蓋修改在該字串後面的記憶體。如果是建立新的字串並在新的字串 上做替換,那麼我們可以自已分配足夠多的記憶體。由於有兩種不同的解決...
劍指 Offer 05 替換空格
劍指 offer 05.替換空格 請實現乙個函式,把字串 s 中的每個空格替換成 20 示例 1 方法一 遍歷新增 由於每次替換從 1 個字元變成 3 個字元,使用字元陣列可方便地進行替換。建立字元陣列地長度為 s 的長度的 3 倍,這樣可保證字元陣列可以容納所有替換後的字元。class solut...
劍指 Offer 05 替換空格
請實現乙個函式,把字串 s 中的每個空格替換成 20 示例 1 限制 0 s 的長度 10000 我的解答 class solution 這道題還是很簡單的,使用replace或者遍歷整個字串,每到空格就新增 20即可。不過在做完後發現,replace和replaceall方法具有差別,replac...