开发者

Insertion at a specified position in a string in java

Before I plan to apply some algorithm, wanted to clarify, whether easier solution is availabl开发者_如何学JAVAe in java for this particular problem.

String str = "This is a test string";

For the above string,

Have to insert at pos 3 - "---"

Have to insert at pos 6 - "~~~~"

How to achieve this? Using stringBuffer , I can use API , insert(pos,char[]);

In first loop , if I insert at pos 3, second pos (pos - 6) is no longer true, To get correct pos second time , have to add no of characters previously added. (i.e. 6+3 =9).

One way is to keep track of characters that I have added. (cumbersome)

But, Is there a way where I can keep on inserting to the original text at specified position, and then make a Union of it or like that ! (basically a better approach) ?

e.g. "This is a test string"

1st loop- Thi---s is a test string

2nd loop- This i~~~~s a test string

finally o/p required is Thi---s i~~~~s a test string.

This is a part of bigger problem , before I approach that , wanted to clarify this.


I'm not sure this is what you're looking for, but you can start from the end, this way the indexes will still be true:

e.g. "This is a test string"
1st loop- This i~~~~s a test string
                ^index 6
2nd loop- Thi---s i~~~s a test string
             ^index 3

I find it convenient when modifying arrays as well...


How about proceeding backwards? Insert at greatest index first.


Suppose if you want to insert at 3 locations, at 3, at 6 and at 1.

This is what I will do:

  1. Sort the indexes in descending order
  2. Then insert.

Indexes will be same for each next insert.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜