Java 给定一个字符串,找到第一个嵌入的整数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9742680/
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
Given a string find the first embedded occurrence of an integer
提问by gmhk
This was asked in an interview:
这是在一次采访中被问到的:
Given in any string, get me the first occurence of an integer.
For example
Str98then it should return 98
Str87uyuy232-- it should return 87
在任何字符串中给出,让我第一次出现整数。
例如
Str98那么它应该返回98
Str87uyuy232-- 它应该返回87
I gave the answer as loop through the string and compared it with numeric characters, as in
我在字符串中循环给出了答案,并将其与数字字符进行了比较,如
if ((c >= '0') && (c <= '9'))
Then I got the index of the number, parsed it and returned it. Somehow he was not convinced. Can any one share the best possible solution?
然后我得到了数字的索引,解析它并返回它。不知怎么的,他并不信服。任何人都可以分享最好的解决方案吗?
采纳答案by mfrankli
There are two issues with this solution.
这个解决方案有两个问题。
Consider the test cases - there are 2 characters '8' and '7', and they both form the integer 87 that you should be returning. (This is the main issue)
This is somewhat pedantic, but the integer value of the character '0' isn't necessarily less than the value of '1', '2', etc. It probably almost always is, but I imagine interviewers like to see this sort of care. A better solution would be
if (Character.isDigit(c)) { ... }
考虑测试用例 - 有 2 个字符 '8' 和 '7',它们都构成了您应该返回的整数 87。(这是主要问题)
这有点迂腐,但字符“0”的整数值不一定小于“1”、“2”等的值。它可能几乎总是如此,但我想面试官喜欢看到这种关心。更好的解决方案是
if (Character.isDigit(c)) { ... }
There are plenty of different ways to do this. My first thought would be:
有很多不同的方法可以做到这一点。我的第一个想法是:
int i = 0;
while (i < string.length() && !Character.isDigit(string.charAt(i))) i++;
int j = i;
while (j < string.length() && Character.isDigit(string.charAt(j))) j++;
return Integer.parseInt(string.substring(i, j)); // might be an off-by-1 here
Of course, as mentioned in the comments, using the regex functionality in Java is likely the best way to do this. But of course many interviewers ask you to do things like this without libraries, etc...
当然,正如评论中提到的,在 Java 中使用正则表达式功能可能是最好的方法。但是当然很多面试官会要求你在没有图书馆等的情况下做这样的事情......
回答by cdeszaq
With a regex, it's pretty simple:
使用正则表达式,它非常简单:
String s = new String("Str87uyuy232");
Matcher matcher = Pattern.compile("\d+").matcher(s);
matcher.find();
int i = Integer.valueOf(matcher.group());
回答by Matt
String input = "Str87uyuy232";
Matcher m = Pattern.compile("[^0-9]*([0-9]+).*").matcher(input);
if (m.matches()) {
System.out.println(m.group(1));
}
回答by Kevin
Just in case you wanted non-regex and not using other utilities.
以防万一您想要非正则表达式而不使用其他实用程序。
here you go
干得好
public static Integer returnInteger(String s)
{
if(s== null)
return null;
else
{
char[] characters = s.toCharArray();
Integer value = null;
boolean isPrevDigit = false;
for(int i =0;i<characters.length;i++)
{
if(isPrevDigit == false)
{
if(Character.isDigit(characters[i]))
{
isPrevDigit = true;
value = Character.getNumericValue(characters[i]);
}
}
else
{
if(Character.isDigit(characters[i]))
{
value = (value*10)+ Character.getNumericValue(characters[i]);
}
else
{
break;
}
}
}
return value;
}
}
回答by jello
You could go to a lower level too. A quick look at ASCII valuesreveals that alphabetical characters start at 65. Digits go from 48 - 57. With that being the case, you can simply 'and' n character against 127 and see if that value meets a threshold, 48 - 57.
你也可以下一个级别。快速查看ASCII 值会发现字母字符从 65 开始。数字从 48 到 57。在这种情况下,您可以简单地对 127 使用“和”n 个字符,看看该值是否满足阈值 48 到 57。
char[] s = "Str87uyuy232".toCharArray();
String fint = "";
Boolean foundNum = false;
for (int i = 0; i < s.length; i++)
{
int test = s[i] & 127;
if (test < 58 && test > 47)
{
fint += s[i];
foundNum = true;
}
else if (foundNum)
break;
}
System.out.println(fint);
Doing this wouldn't be good for the real world (different character sets), but as a puzzle solution is fun.
这样做对现实世界(不同的字符集)不利,但作为拼图解决方案很有趣。
回答by barjak
Using java.util.Scanner
:
使用java.util.Scanner
:
int res = new Scanner("Str87uyuy232").useDelimiter("\D+").nextInt();
The purpose of a Scanner
is to extract tokens from an input (here, a String
). Tokens are sequences of characters separated by delimiters. By default, the delimiter of a Scanner
is the whitespace, and the tokens are thus whitespace-delimited words.
a 的目的Scanner
是从输入(这里是 a String
)中提取标记。标记是由分隔符分隔的字符序列。默认情况下, a 的分隔符Scanner
是空格,因此标记是空格分隔的单词。
Here, I use the delimiter \D+
, which means "anything that is not a digit". The tokens that our Scanner
can read in our string are "87" and "232". The nextInt()
method will read the first one.
在这里,我使用了 delimiter \D+
,意思是“任何不是数字的东西”。我们Scanner
可以在字符串中读取的标记是“87”和“232”。该nextInt()
方法将读取第一个。
nextInt()
throws java.util.NoSuchElementException
if there is no token to read. Call the method hasNextInt()
before calling nextInt()
, to check that there is something to read.
nextInt()
java.util.NoSuchElementException
如果没有要读取的令牌,则抛出。hasNextInt()
在调用之前调用该方法nextInt()
,以检查是否有要读取的内容。