我有一個字符串變量:更換字符串內容,而無需使用替代或的replaceAll
String str = " abc boy abc funny os abc abcifff abc abc boy abc";
我要替換「ABC」爲「」,這將導致:
the boy the funny os the abcifff the the boy the
哪有我這樣做沒有使用replace
或replaceAll
?
我有一個字符串變量:更換字符串內容,而無需使用替代或的replaceAll
String str = " abc boy abc funny os abc abcifff abc abc boy abc";
我要替換「ABC」爲「」,這將導致:
the boy the funny os the abcifff the the boy the
哪有我這樣做沒有使用replace
或replaceAll
?
這聽起來像一個家庭作業問題或類似的問題,所以我會給你一些提示。
(1)看的Java類StringTokenizer
(2)考慮如何使用,在一個循環,工作方式類似(僞):
while there are substrings left to process
get the next substring in s
if that is "abc"
append "the" to the result
else
append s to the result
不要忘了處理之間的空間的話。
規則需要創造性解釋!使用Pattern類!
Pattern.compile("abc").matcher(yourString).replaceAll("the")
因爲,根據意見,在replaceAll
禁令是由於誤解,試試這個:
System.out.println(" abc boy abc funny os abc abcifff abc abc boy abc".replaceAll(
"(?)abc(+|$)", "$1the$2"));
輸出:
男孩的搞笑OS的abcifff中的男孩
爲什麼你不想使用replaceAll? – 2011-04-18 17:18:45
我懷疑這可能是功課。 – 2011-04-18 17:19:29
因爲如果我使用replaceAll方法,它會隨處改變(例如:「abc boy abc abc abc abc abcifff abc abc abc abc」更改爲「男孩有趣的os這個男孩」)但是我只需要任何「 abc「,只有它必須改變。 – shree 2011-04-18 17:23:12