java – 替换string中的重复子字符串
发布时间:2020-12-15 04:22:24 所属栏目:Java 来源:网络整理
导读:我在 java工作,我想采取以下字符串: String sample = "This is a sample string for replacement string with other string"; 我想用“这是一个更大的字符串”替换第二个“字符串”,在一些java魔术之后,输出看起来像这样: System.out.println(sample);"Thi
我在
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函数之外,还有更好的方法吗? 编辑 – 文本“string”将在示例字符串中至少一次,但可能在该文本中多次,偏移将指示哪一个被替换(不总是第二个).因此需要替换的字符串始终是偏移量的字符串. 解决方法
你可以这样做的一种方式..
String s = "This is a sample string for replacement string with other string"; String r = s.replaceAll("^(.*?string.*?)string","$1this is a much larger string"); //=> "This is a sample string for replacement this is a much larger string with other string" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |