this is my code :
public class a {
public static void main(String[] args) {
String a = "12345aaaa##22";
String b = a[-2:];
System.out.println(b);
}
}
how to get last string '22' using java
tha开发者_运维百科nks
Depends on your requirement.
If you need the last two chars from a given String, use substring
:
String lastToChars = input.substring(input.length()-2);
// if you need that number as integer
int value = Integer.parseInt(lastToChars);
If you need everything after ##
(may be a delimiter), do a:
String charsAfterDelimiter = input.split("##")[1];
Some seemingly relevant String methods:
String.substring(start, end)
(or String.substring(start)
):
Returns a new string that is a substring of this string. The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
. Thus the length of the substring isendIndex-beginIndex
.
String.lastIndexOf(str)
:
Returns the index within this string of the rightmost occurrence of the specified substring. The rightmost empty string
""
is considered to occur at the index valuethis.length()
. The returned index is the largest value k such thatthis.startsWith(str, k)
Answering the Question:
You question wasn't that clear, but if I understand you right and you want the last two characters as String, you can do this:
String a = "12345aaaa##22";
System.out.println(a.substring(a.length() - 2));
Output:
22
Take a look at String.lastIndexOf(String)
.
You should use a regular expression if you are trying to retrieve the "last number" of a string.
Something like "([0-9]+)$", for example.
String a = "12345aaaa##22";
int value = Integer.ParseInt(a.substring(a.length() - 2);
System.out.println(value);
or if you don't know 22 position you shoud use this
String a = "12345aaaa##22";
String number = "22";
int position = a.SlastIndexOf("22");
int value = Integer.ParseInt(position+number.lenght());
System.out.println(value);
精彩评论