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 Problem with strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with strings" Watch "Problem with strings" New topic

Problem with strings

Angela Alvarado

Joined: Mar 12, 2003
Posts: 2
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

Joined: Mar 12, 2003
Posts: 5
Hi Angela,
Please replace ur first if block with the following code :

Hope this should help.
Eric Fletcher
Ranch Hand

Joined: Oct 26, 2000
Posts: 188
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.

My theory of evolution is that Darwin was adopted. - Steven Wright
Angela Alvarado

Joined: Mar 12, 2003
Posts: 2
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

Joined: Dec 10, 2001
Posts: 7023
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.

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
I agree. Here's the link:
subject: Problem with strings
It's not a secret anymore!