Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with strings

 
Angela Alvarado
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know this should be a simple solution but I think I've confused myself with the different string methods. My program should create a new string by inserting the second string into the first. The second string should be inserted into the first at the position number given by the user. A push in right direction would be appreciated.

My output:
StringOne = abc
StringTwo = xyz
Position Number = 2
Output:xyzc Output should have been abxyzc
[ fixed code tag -ds ]
[ March 13, 2003: Message edited by: Dirk Schreckmann ]
 
jantar mantar
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Angela,
Please replace ur first if block with the following code :

Hope this should help.
'amit
 
Eric Fletcher
Ranch Hand
Posts: 188
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Angela,
You can also use the StringBuffer insert method, which allows you to specify an offset to insert a second string into an existing String. You create a StringBuffer using the base String as the constructor arg and call the insert method passing the offset and the new String to insert. String indices are 0 based, so make sure you have the right position as the offset. The method returns a new StringBuffer with the inserted characters like so:

Then simply call toString() on the new buffer and that's it. After this runs, resultingString would be "BaseInsertedString". The method throws and exception if the offset is less than zero or greater than the length of the base String.
When working with code to concatenate Strings, it's often more efficient to use StringBuffers instead of the + operator, since that is what the JVM is doing under the hood anyway.
HTH,
E
 
Angela Alvarado
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help! I still don't understand the exception line that gets displayed when using the first code. Hopefully, I'll get the hang of this.
Thanks again.
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the error message that you get?
The code in your initial post won't compile as it has an error. It should use the substring method, not the substrin method.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic