[英]How to swap strings within strings with other strings without replace methods
好的,這是怎么回事。 我需要創建一個方法,它接受三個變量作為參數(a、b 和 c),並以某種方式將字符串 c 與字符串 a 中的字符串 b 交換。
這必須在沒有替換方法的情況下完成,因為這是創建此方法的重點。
所以例子是
"Hello my friend, how are you?", "h", "y"
Result: "Yello my friend, yow are you?"
或者
"Computer programming is great!", "great", "awesome"
Result: "Computer programming is awesome!"
我們給出了charAt()
、 string.substring
、 string.length()
和string.IndexOf()
來解決這個問題。 有任何想法嗎?
嘗試使用regex
。
StringBuffer myStringBuffer = new StringBuffer();
// find all h or H
Pattern myPattern = Pattern.compile("h|H");
Matcher myMatcher = myPattern.matcher("Hello my friend, how are you?");
while (myMatcher.find()) {
// replace all the occurrence with the actual replacement
if (myMatcher.group().equals("h")) {
myMatcher.appendReplacement(myStringBuffer, "y");
} else {
myMatcher.appendReplacement(myStringBuffer, "Y");
}
}
myMatcher.appendTail(myStringBuffer);
System.out.println(myStringBuffer);
輸出:
Yello my friend, yow are you?
我認為編寫確切的代碼是不對的,因為這顯然是學校作業。 這是一項非常簡單的任務,在閱讀 文檔后,您應該知道如何實現它。 如果不是這里的小提示
You have to chceck wheter string b is substring of a if yes split a into two strings without b and put c between them.
所有這些都可以使用您提到的方法完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.