Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String's insert

 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
since String class doesnt provide a insert method for such purpose, what's the equivalent method can do such a job?
 
Jari Timonen
Ranch Hand
Posts: 232
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm not sure what you mean, but StringBuilder has insert method. See API: http://java.sun.com/j2se/1.5.0/docs/api/
 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi!
I know what you means!String class doesnt provide a insert method,but we can use equivalent method to instead.
for example,we want to insert "Fu" to "Jiadong":

or,if you donnot know the index of the string,you can do like this:
 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi!
I know what you means!String class doesnt provide a insert method,but we can use equivalent method to instead.
for example,we want to insert "Fu" to "Jiadong":

or,if you don't know the index of the string,you can do like this:
 
adam Lui
Ranch Hand
Posts: 186
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that's cool man thanks Jia

it looks so not appealing to me that insert is not included in the String class!
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
String objects are immutable in Java, so that's why the String class doesn't provide any methods for changing its contents. As already stated, you can either use string concatenation or StringBuilder/StringBuffer whenever you need an editable string. (Note that most compilers will automatically use StringBuffer or StringBuilder for expressions involving multiple string concatenations.)

Here are a pair of StringBuilder-based code snippets to do the same thing as the two programs which Fudong posted:

[ November 13, 2007: Message edited by: Kelvin Lim ]
 
Vikrant Sahdev
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code example by Jia Fudong : is a loose workaround the insert functionality. It will have to be modified in circumstances like when multiple instances of same char occur in which case indexOf() to look for in subString() wont work that good.
I will suggest StringBuilder class method .
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic