0

I am wondering if using a for loop to determine if an integer is inside of a string, would be the best option. But I am not so sure.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • @Holt If I may speak for the OP, that is a different question. This question is poorly written, but it does clearly ask for how to find an integer anywhere in the string, not if the whole string is an integer. – Charlie Armstrong Dec 04 '20 at 18:35
  • Contains only an integer and nothing else or contains text mixed with an integer? – knittl Dec 04 '20 at 18:36
  • 1
    @OP, we are going to need some clarification. What defines an integer in a string? Digits not followed by a dot `.`? Do the digits have to be surrounded by spaces? You could check for parseable integers in your string, but note that you could also capture parts of floating point numbers. – Charlie Armstrong Dec 04 '20 at 18:38
  • `if ("There's a number 123 in this string.".replaceAll("[^\\d]", "").length() > 0) { System.out.println("Yup...there's a number in that there string."); } else { System.out.println("Nope...Nothing!"); }` – DevilsHnd - 退職した Dec 06 '20 at 01:51

1 Answers1

0

Hello, is there a specific logical way to determine if there is an integer in a String?

A simple solution is to use regex. The regex, \d+ means a sequence of one or more digit characters.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws IllegalArgumentException {
        String str = "Hello123World";
        Matcher matcher = Pattern.compile("\\d+").matcher(str);
        if (matcher.find()) {
            System.out.println("The integer inside the text is " + matcher.group());
        } else {
            System.out.println("There is no integer inside the text.");
        }
    }
}

Output:

The integer inside the text is 123
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • 1
    I think this is a good solution for your test case, but I think we need more information from the OP. What about hexadecimal numbers? Your code could skip those entirely. Or what if the OP doesn't want to capture floating point numbers? Your code would count `123.5` as two integers. The OP just wasn't clear enough. – Charlie Armstrong Dec 04 '20 at 18:40