开发者

how to get last string '22' using java

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 index endIndex - 1. Thus the length of the substring is endIndex-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 value this.length(). The returned index is the largest value k such that this.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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜