给定一个字符串,找到第一个嵌入的整数 [英] Given a string find the first embedded occurrence of an integer

查看:86
本文介绍了给定一个字符串,找到第一个嵌入的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在接受采访时询问:


在任何字符串中给出,让我第一次出现整数。

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

例如

Str98 然后它应该返回 98

Str87uyuy232 - 它应该返回 87

Str87uyuy232 -- it should return 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?

推荐答案

此解决方案存在两个问题。

There are two issues with this solution.


  1. 考虑测试用例 - 有2个字符'8'和'7',它们都形成你应该返回的整数87 。 (这是主要问题)

  1. 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)

这有点迂腐,但字符'0'的整数值不一定小于'的值' 1','2'等等。它可能几乎总是如此,但我想访谈者喜欢看到这种关怀。更好的解决方案是

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)){...}

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

当然,如评论中所述,使用Java中的正则表达式功能可能是执行此操作的最佳方式。但是当然很多面试官要求你做这样的事情,没有图书馆等等......

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...

这篇关于给定一个字符串,找到第一个嵌入的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆