Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the last characters in a String in Java, regardless of String size

Tags:

java

string

I'm looking for a way to pull the last characters from a String, regardless of size. Lets take these strings into example:

"abcd: efg: 1006746" "bhddy: nshhf36: 1006754" "hfquv: nd: 5894254" 

As you can see, completely random strings, but they have 7 numbers at the end. How would I be able to take those 7 numbers?

Edit:

I just realized that String[] string = s.split(": "); would work great here, as long as I call string[2] for the numbers and string[1] for anything in the middle.

like image 282
PuppyKevin Avatar asked Jul 14 '10 06:07

PuppyKevin


People also ask

How do you get the last character of a string in Java?

By call charAt() Method If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str. charAt(11)".

How do you get the last few characters of a string?

To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string.

How do I get the last alphabet of a string?

The idea is to use charAt() method of String class to find the first and last character in a string. The charAt() method accepts a parameter as an index of the character to be returned. The first character in a string is present at index zero and the last character in a string is present at index length of string-1 .

How do you split the last character of a string?

To split a string on the last occurrence of a substring:, use the lastIndexOf() method to get the last index of the substring and call the slice() method on the string to get the portions before and after the substring you want to split on.


1 Answers

How about:

String numbers = text.substring(text.length() - 7); 

That assumes that there are 7 characters at the end, of course. It will throw an exception if you pass it "12345". You could address that this way:

String numbers = text.substring(Math.max(0, text.length() - 7)); 

or

String numbers = text.length() <= 7 ? text : text.substring(text.length() - 7); 

Note that this still isn't doing any validation that the resulting string contains numbers - and it will still throw an exception if text is null.

like image 62
Jon Skeet Avatar answered Oct 11 '22 17:10

Jon Skeet