【问题标题】:Replacing text in String won't work [duplicate]替换字符串中的文本不起作用[重复]
【发布时间】:2014-06-23 06:27:30
【问题描述】:

我正在尝试编写一种方法,将字符串中 html 代码的一些变量替换为例如图片来源等。

String html = "<img src='IMAGE_SOURCE' width='IMAGE_WIDTH' align='IMAGE_ALIGN";

现在这是我的字符串,我已经编写了三个方法:

public void setImageSource(String src) {
  html.replace("IMAGE_SOURCE", "Here comes the source for the image");
}

public void setImageWidth(String width) {
  html.replace("IMAGE_SOURCE", "Here comes the width for the image");
}

public void setImageAlign(String align) {
  html.replace("IMAGE_SOURCE", "Here comes the align for the image");
}

方法被调用,但字符串“html”不会改变。有什么建议吗?

【问题讨论】:

  • 字符串是不可变的。

标签: java android string


【解决方案1】:

您需要修改您的代码,如:

html = html.replace("IMAGE_SOURCE", "Here comes the width for the image");

Java 中的字符串是常量,也就是说你不能改变字符串的值,你需要一个新的字符串来存储你的操作结果

【讨论】:

  • 是的,我完全忘记了这一点。谢谢!
【解决方案2】:

我看到的另一个潜在问题:

您正在使用名为“src”、“width”、“height”的参数,但您没有在函数中使用这些变量。你的意思是做类似的事情:

String edited = src.replace("IMAGE_SOURCE", "Here comes the source for the image");
return edited;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-07
    • 2017-07-25
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 2013-09-14
    相关资源
    最近更新 更多