【发布时间】:2014-11-05 20:13:59
【问题描述】:
我在java中工作,我想获取以下字符串:
String sample = "This is a sample string for replacement string with other string";
我想用“这是一个更大的字符串”替换第二个“字符串”,经过一些 java 魔术后,输出将如下所示:
System.out.println(sample);
"This is a sample string for replacement this is a much larger string with other string"
我确实有文本开始位置的偏移量。在这种情况下,40 和文本被替换为“字符串”。
我可以做一个:
int offset = 40;
String sample = "This is a sample string for replacement string with other string";
String replace = "string";
String replacement = "this is a much larger string";
String firstpart = sample.substring(0, offset);
String secondpart = sample.substring(offset + replace.length(), sample.length());
String finalString = firstpart + replacement + secondpart;
System.out.println(finalString);
"This is a sample string for replacement this is a much larger string with other string"
但是除了使用子字符串 java 函数之外,还有更好的方法吗?
编辑-
文本“字符串”将至少在示例字符串中出现一次,但可能在该文本中出现多次,偏移量将决定哪个被替换(并不总是第二个)。所以需要被替换的字符串总是偏移处的那个。
【问题讨论】:
-
您是否只是想有效地制作“这是一个用于替换的示例字符串,这是一个更大的字符串与其他字符串”,或者您是否正在寻找一种方法来替换“字符串”的特定实例未知字符串?
-
为了解决“用替换字符串替换从源字符串的偏移量N开始的M字符”的问题,我会说不——据我所知,没有比
substring更好的方法了。除非 Apache Commons 或其他第三方库中有什么东西。
标签: java regex string replace substring