aspose file tools*
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


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with strings" Watch "Problem with strings" New topic
Author

Problem with strings

Angela Alvarado
Greenhorn

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
Greenhorn

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

Hope this should help.
'amit
Eric Fletcher
Ranch Hand

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


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

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
Sheriff

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: http://aspose.com/file-tools
 
subject: Problem with strings
 
Similar Threads
Sorting arrayLIst containing value objects
basic stringing need helps
Java/JBuilder - Anyone with brains please help
Where to ask questions about cattledrive assignments?
synchronization