• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

char insertion in strings

 
jacq carballo
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
tia
jacq
 
Michael Yuan
author
Ranch Hand
Posts: 1427
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For JDK 1.4, you could use regular expression: Find the "," pattern and replace them with ",,".
 
Ivor Horton
Author
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Karl Laird
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic