문제

I want insert multiple words in a String, But offset is relative to the original String:

StringBuffer sb = new StringBuffer("abcdefghijk");
sb.insert(3,"123");
sb.insert(5,"456");
System.out.println(sb); 

Result:

abc124563defghijk

I'd like the Result is:

abc123de456fghijk

How can I do? Thanks for any suggestion.

도움이 되었습니까?

해결책

Reverse the order of the two inserts, and you'll get the expected result. More generally, start with the larger insertion indices and proceed to the smaller.

It is also worth noting that StringBuilder should be preferred to StringBuffer.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top