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.
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)".
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.
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With