aspose file tools*
The moose likes Beginning Java and the fly likes how do you chop the last 7 digits off of a String in JAVA? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "how do you chop the last 7 digits off of a String in JAVA?" Watch "how do you chop the last 7 digits off of a String in JAVA?" New topic
Author

how do you chop the last 7 digits off of a String in JAVA?

peter moss
Greenhorn

Joined: Aug 22, 2003
Posts: 9
Hi,
I have a string that looks something like this
String test = "test0001234567";
I want to just take the last 7 digits of that string so I can do stuff with just those 7 digits later (i.e. put them into a database)
How do I do that?
Thanks
Rob Ross
Bartender

Joined: Jan 07, 2002
Posts: 2205
This is definately a Java-In-General question so I'm moving it there.
You want to use the substring method of class String, btw. Check out the JavaDocs for String.substring.


Rob
SCJP 1.4
Joe Pluta
Ranch Hand

Joined: Jun 23, 2003
Posts: 1376
Just be careful - the parameters for the substring method were definitely designed by compiler guys .
The first parameter is cool - it's the index of the first character. But the send parameter is NOT the number of characters. It is also not the index of the last character in the substring. It is the index of the last character PLUS ONE. That's cool if you need to use that index as the beginning of your next call to substring, but besides that it's VERY confusing.
Luckily for you, there is a version of substring that doesn't require the second parameter. Using that one is a little easier. If there are N character in the string, you need to start at index N-7. That will get you the last seven characters of the string.
String last7 = test.substring(test.length()-7);
Note that this will blow up if the string is less than seven characters long.
Joe
peter moss
Greenhorn

Joined: Aug 22, 2003
Posts: 9
Thanks. That was very helpful..
I have another question though. Say I now have a bunch of ID numbers in a string called
idnumbers[]
the values lets say are 1234567, 7654321, 9999967, 2222222
Now how do I just disiplay the ones that END in 67 ?
Thanks a ton.
Jason Menard
Sheriff

Joined: Nov 09, 2000
Posts: 6450
Use the endsWith() method of String. For example:

[ August 29, 2003: Message edited by: Jason Menard ]
 
wood burning stoves
 
subject: how do you chop the last 7 digits off of a String in JAVA?