简体   繁体   English

从字符串中获取最后一个数字

[英]Get last number from string

I want to get the last character of a string and if it's a even number to do different actions based on that. 我想获取字符串的最后一个字符,如果它是偶数,则可以基于该字符执行不同的操作。 Simple example: 简单的例子:

Server_3

First I want to get the last value 3 首先我要获得最后的值3

            String str = "Server_3";
            str.charAt(str.length()-1)

The problem is next how to construct the logic to have different cased based on that is this a even number or not. 接下来的问题是如何基于是否为偶数来构造具有不同大小写的逻辑。 Can you help me to complete this? 你能帮我完成这个吗?

The correct code is: 正确的代码是:

if (Integer.valueOf(str.charAt(str.length()-1) + "") % 2 == 0) {
    // Even logic
} else {
    // Odd logic
}

Or.... to reduce method calls and the get rid of the funky string concatenation: 或者....以减少方法调用并摆脱时髦的字符串连接:

if ((str.charAt(str.length()-1) - '0') % 2) {
    // Even logic
} else {
    // Odd logic
}

Convert to integer and check for even 转换为整数并检查偶数

if(Integer.valueOf(str.charAt((str.length()-1) + "") % 2 ==0) {
    // do your work here
}

使用模( % )运算符: i % 2如果i为偶数,则i % 2为0,如果i为奇数,则为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM