This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
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


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: substring