gpt4 book ai didi

java - 给定一个字符串,找到第一个嵌入的整数

转载 作者:IT老高 更新时间:2023-10-28 21:04:25 25 4
gpt4 key购买 nike

这是在采访中被问到的:

Given in any string, get me the first occurence of an integer.

For example

Str98 then it should return 98

Str87uyuy232 -- it should return 87

我通过字符串循环给出答案,并将其与数字字符进行比较,如

if ((c >= '0') && (c <= '9'))

然后我得到了数字的索引,解析它并返回它。不知怎的,他并不相信。任何人都可以分享最好的解决方案吗?

最佳答案

使用正则表达式非常简单:

String s = new String("Str87uyuy232");
Matcher matcher = Pattern.compile("\\d+").matcher(s);
matcher.find();
int i = Integer.valueOf(matcher.group());

(Thanks to Eric Mariacher)

关于java - 给定一个字符串,找到第一个嵌入的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9742680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com