[英]Android - how to replace part of a string by another string?
我有一些帶有一些數字和英語單詞的字符串,我需要通過找到它們並將它們替換為這個單詞的本地化版本來將它們翻譯成我的母語。 您知道如何輕松實現替換字符串中的單詞嗎?
謝謝
編輯:
我試過(字符串“to”的一部分應該替換為“xyz”):
string.replace("to", "xyz")
但它不起作用......
它正在工作,但它不會修改調用者對象,而是返回一個新的字符串。
所以你只需要將它分配給一個新的 String 變量,或者給它自己:
string = string.replace("to", "xyz");
或者
String newString = string.replace("to", "xyz");
API 文檔
public String replace (CharSequence target, CharSequence replacement)
從:API 級別 1
復制此字符串,用另一個序列替換指定目標序列的出現。 字符串從頭到尾進行處理。
參數
target
要替換的序列。replacement
替換順序。 返回結果字符串。
如果目標或替換為空,則拋出NullPointerException
。
您可能會感興趣:
在java中,字符串對象是不可變的。 不可變僅意味着不可修改或不可更改。
一旦創建了字符串對象,它的數據或狀態就不能更改,但會創建一個新的字符串對象。
String str = "to";
str.replace("to", "xyz");
就試一試吧 :)
在kotlin中沒有replaceAll,所以我創建了這個循環來替換字符串或任何變量中的重復值。
var someValue = "https://www.google.com.br/"
while (someValue.contains(".")) {
someValue = someValue.replace(".", "")
}
Log.d("newValue :", someValue)
// in that case the stitches have been removed
//https://wwwgooglecombr/
雷卡塞魯
我注意到您在 2011 年發表了評論,但我認為無論如何我都應該發布此答案,以防萬一有人需要“替換原始字符串”並遇到此答案..
我以 EditText 為例
// 給目標文本框一個名字
EditText textbox = (EditText) findViewById(R.id.your_textboxID);
// 要替換的字符串
String oldText = "hello"
String newText = "Hi";
String textBoxText = textbox.getText().toString();
// 用返回的字符串替換字符串
String returnedString = textBoxText.replace( oldText, newText );
// 使用返回的字符串替換文本框內的新字符串
textbox.setText(returnedString);
這是未經測試的,但這只是使用返回的字符串用 setText() 替換原始布局字符串的示例!
顯然這個例子要求你有一個 ID 設置為 your_textboxID 的 EditText
你只犯了一個錯誤。
在那里使用replaceAll()
函數。
例如
String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.