java 从字符串的末尾获取整数(可变长度)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2620591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:03:09  来源:igfitidea点击:

Get the Integer from the end of a string (variable length)

java

提问by black666

I have a string of a variable length and at the end of the string are some digits. What would be the best / efficient way, to parse the string and get the number from the end as an Integer?

我有一个可变长度的字符串,字符串的末尾是一些数字。解析字符串并从末尾获取数字作为整数的最佳/有效方法是什么?

The String and the digits at the end can can be of any length. For example:

字符串和末尾的数字可以是任意长度。例如:

abcd123 --> 123
abc12345 --> 12345
ab4cd1 --> 1

回答by VonC

Something along the line of:

沿线的东西:

final static Pattern lastIntPattern = Pattern.compile("[^0-9]+([0-9]+)$");
String input = "...";
Matcher matcher = lastIntPattern.matcher(input);
if (matcher.find()) {
    String someNumberStr = matcher.group(1);
    int lastNumberInt = Integer.parseInt(someNumberStr);
}

could do it.

能做到这。

This isn't necessary the "most efficient" way, but unless you have a critical bottleneck around this code (as: extract int from millions of String), this should be enough.

这不是“最有效”的方式,但除非您在此代码周围存在关键瓶颈(例如:从数百万个字符串中提取 int),否则这应该足够了。

回答by polygenelubricants

Other solutions provided here are fine, so I'll provide this one just to be a bit different:

此处提供的其他解决方案很好,所以我将提供这个解决方案只是为了有所不同:

public static BigInteger lastBigInteger(String s) {
    int i = s.length();
    while (i > 0 && Character.isDigit(s.charAt(i - 1))) {
        i--;
    }
    return new BigInteger(s.substring(i));
}
  • It manually looks for the position of the last non-Character.isDigit(char)
    • It still works if the input is all digit
  • It uses BigInteger, so it can handle really large numbers at the end of really long strings.
    • Use Integer.parseIntor Long.parseLongif either sufffice
  • 它手动寻找最后一个非Character.isDigit(char)
    • 如果输入全是数字,它仍然有效
  • 它使用BigInteger,因此它可以处理非常长的字符串末尾的非常大的数字。
    • 使用Integer.parseInt或者Long.parseLong如果任何一个就足够了

回答by paxdiablo

Best is such a subjective term :-) Unless you're going to being doing this quite a bit (in which case performance may take priority over readability), I'd just go with my first gut feeling:

最好是这样一个主观的术语:-) 除非你打算这样做很多(在这种情况下,性能可能优先于可读性),我只会用我的第一个直觉:

int n = 0;
try {
    n = Integer.parseInt (str.replaceFirst("^.*\D",""));
} catch (Exception e) {}

回答by Matthew T. Staebler

int getTrailingInteger(String str)
{
    int positionOfLastDigit = getPositionOfLastDigit(str);
    if (positionOfLastDigit == str.length())
    {
        // string does not end in digits
        return -1;
    }
    return Integer.parseInt(str.substring(positionOfLastDigit));
}

int getPositionOfLastDigit(String str)
{
    int pos;
    for (pos=str.length()-1; pos>=0; --pos)
    {
        char c = str.charAt(pos);
        if (!Character.isDigit(c)) break;
    }
    return pos + 1;
}

回答by Martijn Courteaux

I'm going to do this without regex!

我要在没有正则表达式的情况下做到这一点!

Check out my update!

看看我的更新!

public static int getLastInt(String line)
{
    int offset = line.length();
    for (int i = line.length() - 1; i >= 0; i--)
    {
        char c = line.charAt(i);
        if (Character.isDigit(c))
        {
            offset--;
        }
        else
        {
            if (offset == line.length())
            {
                 // No int at the end
                 return Integer.MIN_VALUE;
            }
            return Integer.parseInt(line.substring(offset));
        }
    }
    return Integer.parseInt(line.substring(offset));
}

This works perfect.

这工作完美。

回答by slipset

private int intAtEnd(String string) {
        int i, j;
        i = j = string.length();
        while (--i > 0) {
            if (Character.isDigit(string.charAt(i))) continue;
            i++;
            break;
        } 
        if (j - i > 1) return Integer.parseInt(string.substring(i));
        return -1;
    }

回答by ossobuko

There is already many good answers, I just wanted to give my two cents.

已经有很多好的答案了,我只想给我的两分钱。

I know running parseInt()in a loop is not an efficient way but for sake of simplicity.

我知道在循环中运行parseInt()不是一种有效的方式,但为了简单起见

public static int getIntFromEnd (String string) {
  for (int a = string.length()-1; a >=0; a--)
  try {
    int result = Integer.parseInt(string.substring(a,string.length()));
    // the whole string is integer
    if(a == 0) return result;
  } catch (Exception e) {
    // there is no numbers at the end
    if(a == string.length()-1) break;
    return Integer.parseInt(string.substring(a+1,string.length()));
  }
  // there is no numbers
  return -1;
}

TESTED AGAINST OTHER ANSWERS:

针对其他答案进行测试:

I have run some tests against the accepted answer, and this code runs 7 to 10 times faster.

我已经针对已接受的答案运行了一些测试,此代码的运行速度提高了 7 到 10 倍

Then I tried it against the second most upvoted answer, and this code runs 3 to 4 times faster.

然后我针对第二个最受支持的答案进行尝试,此代码的运行速度提高了 3 到 4 倍

回答by Mansingh Shitole

public int getIntFromEndOfString(String inpStr){
    int revVal = 0;
    boolean flag = false;
    String reverseNo  = "", result = "";
    for (int i = inpStr.length()-1; i >= 0 ; i--) {
        reverseNo = String.valueOf(inpStr.charAt(i));
        if(!flag)
        if(reverseNo.equals("0") ||reverseNo.equals("1") || reverseNo.equals("2") || reverseNo.equals("3")
                | reverseNo.equals("4") || reverseNo.equals("5") || reverseNo.equals("6") || reverseNo.equals("7")
                || reverseNo.equals("8") || reverseNo.equals("9")){
            revVal = Integer.parseInt(reverseNo);
            result+= String.valueOf(revVal);
        }else{
            inpStr = result;
            i = inpStr.length();
            flag = true;
            result = "";
        }else{
            result += reverseNo;
        }
    }
    revVal = Integer.parseInt(result);
    return revVal;
}

回答by Eyal Schneider

In general I prefer clear and short code, but if performance is really your first priority here, consider something like:

一般来说,我更喜欢清晰和简短的代码,但如果性能真的是你的首要任务,请考虑以下内容:

private static int getNum(String s){
    int res = 0;
    int p = 1;
    int i = s.length()-1;
    while(i >= 0){
        int d = s.charAt(i) - '0';
        if (d>=0 && d<=9)
            res += d * p;
        else
            break;
        i--;
        p *= 10;
    }

    return res;     
}

It doesn't use any complex string/regex operations. But again - if performance is not an issue, please use the other techniques presented above.

它不使用任何复杂的字符串/正则表达式操作。但同样 - 如果性能不是问题,请使用上面介绍的其他技术。

回答by Hymankav

Loop through each character looking for non-numeric characters. When one is found chop it and everything off before it. After the loop has run cast the result to int.

遍历每个字符以查找非数字字符。当一个人被发现时,把它砍掉,然后把它之前的所有东西都砍掉。循环运行后,将结果强制转换为 int。