2

如何将子字符串连接重构为StringBuilder

        String line = "this is my start and my end string";
        int start = line.indexOf("start");
        line = line.substring(0, start) + line.substring(start + 5);

        int end = line.indexOf("end");
        line = line.substring(0, end) + line.substring(end + 3);
            //result: this is my and my string";

使用 StringBuilder 时,相同的代码会是什么样子?当我想一个接一个地多次执行子字符串时?

4

5 回答 5

4

如果您的问题是“如何从字符串中反复删除子字符串”,您可以尝试以下操作:

StringBuilder line = new StringBuilder("this is my start and my end string");
int start = line.indexOf("start");
line.delete(start, start + 5);
int end = line.indexOf("end");
line.delete(end, end + 3);
String result = sb.toString()

创建一次 StringBuilder,然后操作其内容。

于 2013-10-01T10:08:37.673 回答
1

这样的事情可能是:

    StringBuilder line = new StringBuilder("this is my **start** and my **end** string");
    int start = line.indexOf("start");
    line = new StringBuilder(line.substring(0, start).append(line.substring(start + 5)));

    int end = line.indexOf("end");
    line = new StringBuilder(line.substring(0, end).append(line.substring(end + 3)));
于 2013-10-01T10:03:58.953 回答
1

你的意思是这样的吗?还是我理解错了?

String line = "this is my start and my end string";
int start = line.indexOf("start");
int end = line.indexOf("end");
StringBuilder sb = new StringBuilder();
sb.append(line.substring(0, start);
sb.append(line.substring(start + 5);
sb.append(line.substring(0, end);
sb.append(line.substring(end + 3);
String result = sb.toString()
于 2013-10-01T10:04:34.770 回答
0

如果我没记错的话,StringBuilder 有它自己的 indexOf 和子字符串实现。该问题的主要关注点似乎是放弃使用 String,而 StringBuilder 的主要功能仍然是串联。

所以http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html可以帮助你找到相关的方法,你可以继续使用 StringBuilder 和 .append() 方法和你的字符串查找和子字符串方法。

于 2013-10-01T10:14:22.620 回答
0

尝试

String line = "this is my start and my end string";
    int start = line.indexOf("start");
    StringBuilder stringBuilder = new StringBuilder();
    stringBuilder.append(line.substring(0, start));
    stringBuilder.append(line.substring(start + 5));

    int end = line.indexOf("end");
    stringBuilder.append(line.substring(0, end));
    stringBuilder.append(line.substring(end + 3));
    System.out.println("StringBuilder : "+stringBuilder.toString());
于 2013-10-01T10:06:12.030 回答