aspose file tools*
The moose likes Beginning Java and the fly likes substring Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "substring" Watch "substring" New topic
Author

substring

Melinda Wilson
Ranch Hand

Joined: Jul 05, 2001
Posts: 35
How does the substring work?
for example I want to take a phone number 1234567
and place a "-" after the third digit?
I know this is such a simple solution but the books I have do not do a good job in explaining how or give any good examples.
Thank you.
kyle amburn
Ranch Hand

Joined: Jul 29, 2001
Posts: 64
Hi-
String s = "1234567";
String s1 = s.subString(0,3);
String s2 = s.substring(3, s.length());
System.out.println(s1 + "-" s2);
Output:
123-4567
Strings are immutable so you cannot change the String object itself. To get a substring you have to use the beginIndex as the index directly before the character you want and endIndex as the character directly after the one you want. Picture int like this.
String = 1 2 3 4 5 6 7
Index = 0 1 2 3 4 5 6 7
To get String 123 you need to use index 0 and 3. The indexes are before and after the charaters when you use a substring. so String.substring(3,3) will not return anything.
Kyle

[This message has been edited by kyle amburn (edited August 08, 2001).]
Melinda Wilson
Ranch Hand

Joined: Jul 05, 2001
Posts: 35
Thank you Kyle, you did a very good job explaining this.
again thank you.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: substring