File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes char insertion in strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "char insertion in strings" Watch "char insertion in strings" New topic

char insertion in strings

jacq carballo
Ranch Hand

Joined: Feb 10, 2002
Posts: 42
for the following example:
string: hello, world
char to insert: ,
result: hello,, world
algo: use indexOf to look for the char

for the following example:
string: hello, world, bye
char to insert: ,
result: hello,, world,, bye
algo: use indexOf and lastIndexOf to look for the char

for the following example:
string: hello, world, bye, world
char to insert: ,
result: hello,, wolrd,, bye,, world

algo: iterate thru the string and look for the char
My question is: for the last example, is there an easier way to insert a char to a string where there are multiple appearances of the given character to search? i mean, for the last one, since the string is short, it would be simple to iterate thru all the characters of the given string. but if you are to iterate thru a string of, say, 1000 character, it will take a long time.
Michael Yuan
Ranch Hand

Joined: Mar 07, 2002
Posts: 1427
For JDK 1.4, you could use regular expression: Find the "," pattern and replace them with ",,".

Seam Framework:
Ivor Horton
Ranch Hand

Joined: Mar 22, 2002
Posts: 67
Hi jacq,
Take care not to confuse programming convenience with the process necessary to achieve a result. Unless a string is sequenced in some way, or has some special indexing mechanism designed to enable characters to be found faster, the ONLY way to find a particular character is to search. There may be special methods such as indexOf() in the String class for finding a particular character, but such methods will still search starting at the first character. The advantage of such a method will be that it is coded optimally to accomplish the search in as short a time as possible.

Ivor Horton<br />Author of the Beginning Java Series including the new <a href="" target="_blank" rel="nofollow">Beginning Java 2 SDK 1.4 Edition</a>
Karl Laird
Ranch Hand

Joined: Jul 14, 2001
Posts: 67
Also remember stricly speaking you cannot insert a char into a String - Strings are immutable. A new string would need to be created or use a StringBuffer

The Eagle sneers at the Peacock<p>Systems Administrator<br />OrderWare Solutions Ltd<br /><a href="" target="_blank" rel="nofollow"></a>
I agree. Here's the link:
subject: char insertion in strings
It's not a secret anymore!