繁体   English   中英

StringBuilder - 完全替换现有字符串。 任何方法?

[英]StringBuilder - replace existing string entirely. Any method?

我看到现有代码中的字符串用法有多个连接。 声纳代码覆盖率建议使用StringBuilder。 我正在更新代码以使用StringBuilder。 但我想知道如何使用新字符串有效地覆盖现有内容。

在字符串表示中,如下所示:

String query = "select...";
if ( x ) {
    query = "select xyz...";
}

使用StringBuilder,我使用了这个:

 StringBuilder query = new StringBuilder("select...");
 if ( x ) {
     // I need to overwrite the existing stringbuilder content here
     query = new StringBuilder("Select xyz..");
        //or
     query = query.replace(,,,);
        //or
     //Anything better
 }

我希望有一个方法,如:

 query.replace("new string");

用新字符串覆盖整个现有字符串。 但它不可用。

query.replace(0,query.length(), "new string");

应该管用。

这是一个解决方案,而不是最优雅的解决方案,使用StringBuilder.replace(int start, int end, String str)
假设有两个条件:

  • 条件1:你想用“ xxx ”替换“ ele
  • 条件2:你想用“ yyy ”替换“ ...

请尝试以下方法

StringBuilder query = new StringBuilder("select...");
String x = "ele";

String term1 = "ele";
String newTerm1 = "xxx";
String term2 = "...";
String newTerm2 = "yyy";

if ( x.equals(term1) ) {
    int start = query.indexOf(term1);
    int end = start + term1.length();
    query.replace(start, end, newTerm1);

}
else if (x.equals(term2)){
    int start = query.indexOf(term2);
    int end = start + term2.length();
    query.replace(start, end, newTerm2);
}
System.out.println(query.toString());

对于您的用例,以下内容似乎很完美:

private static final String SELECT_PRE = "Select";
private static final String SELECT_POST = "...";
StringBuilder query = new StringBuilder(SELECT_PREFIX+SELECT_POST);
if ( x ) {
     query = query.insert(SELECT_PREFIX.length(), " xyz");
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM