Android-如何用另一个字符串替换字符串的一部分?


69

我有一些带有一些数字和英文单词的字符串,我需要通过找到它们并将其替换为该单词的本地化版本,将它们翻译成我的母语。您知道如何轻松实现替换字符串中的单词吗?

谢谢

编辑:

我已经尝试过(字符串“ to”的一部分应替换为“ xyz”):

string.replace("to", "xyz")

但这不起作用...

Answers:


185

它正在工作,但是不会修改调用者对象,而是返回一个新的String。
因此,您只需要将其分配给新的String变量或自身即可:

string = string.replace("to", "xyz");

要么

String newString = string.replace("to", "xyz");

API文件

public String replace (CharSequence target, CharSequence replacement) 

由于:API级别1

复制此字符串,用另一个序列替换指定目标序列的出现。从头到尾处理字符串。

参量

  • target 替换顺序。
  • replacement 更换顺序。

返回结果字符串。 如果目标或替换为null,则
抛出该异常 NullPointerException


谢谢,这就是我想要的
Waypoint,

2
@rekaszeru谢谢...您的回答非常有帮助。
VJ

如何替换多象物体?例如,Replace letter h or l
Ruchir Baronia'2

2

可能对您感兴趣:

在Java中,字符串对象是不可变的。不可变只是意味着不可更改或不可更改。

创建字符串对象后,其数据或状态便无法更改,但会创建一个新的字符串对象。



0

在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/

-2

雷卡塞鲁

我注意到您在2011年发表了评论,但我认为无论如何我都应该发布此答案,以防万一有人需要“替换原始字符串”并遇到此答案..

我以一个EditText为例


//给目标文本框起一个名字

 EditText textbox = (EditText) findViewById(R.id.your_textboxID);

//替换为STRING

 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。


-3

您只犯了一个错误。

replaceAll()在那边使用功能。

例如

String str = "Hi";
String str1 = "hello";
str.replaceAll( str, str1 );

8
-该replaceAll() 函数都不会更改原始字符串,因此不会返回处理后的字符串!
rekaszeru 2011年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.