如何替换字符串的子字符串 [英] How to replace a substring of a string

查看:106
本文介绍了如何替换字符串的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串字符串,就像这样:

Assuming I have a String string like this:

"abcd=0; efgh=1"

我希望用dddd替换abcd。我试过这样做:

and I want to replace "abcd" by "dddd". I have tried to do such thing:

string.replaceAll("abcd","dddd");

它不起作用。有什么建议?

It does not work. Any suggestions?

编辑:
更具体一点,我在Java工作,我正在尝试解析HTML文档,具体是< script> 标签。我已经找到了如何将这个内容解析为字符串的方法:

To be more specific, I am working in Java and I am trying to parse the HTML document, concretely the content between <script> tags. I have already found a way how to parse this content into a string:

 if(tag instanceof ScriptTag){
        if(((ScriptTag) tag).getStringText().contains("DataVideo")){
            String tagText = ((ScriptTag)tag).getStringText();
      }
}

现在我必须找到一种方法来替换一个子串由另一个。

Now I have to find a way how to replace one substring by another one.

推荐答案

您需要使用 replaceAll()方法的返回值。 replaceAll()不替换当前字符串中的字符,它返回一个带替换字符的新字符串。

You need to use return value of replaceAll() method. replaceAll() does not replace the characters in the current string, it returns a new string with replacement.



  • 字符串对象是不可变的,它们的值在创建后无法更改。

  • 您可以使用replace()而不是replaceAll()如果你不需要正则表达式。



    String str = "abcd=0; efgh=1";
    String replacedStr = str.replaceAll("abcd", "dddd");

    System.out.println(str);
    System.out.println(replacedStr);

输出

abcd=0; efgh=1
dddd=0; efgh=1

这篇关于如何替换字符串的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆