This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

substring

 
Melinda Wilson
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Kyle, you did a very good job explaining this.
again thank you.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic