java 添加重复字符串_java – 替换string中的重复子字符串

我在

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”将在示例字符串中至少一次,但可能在该文本中多次,偏移将指示哪一个被替换(不总是第二个).因此需要替换的字符串始终是偏移量的字符串.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值