0

Let's say you have a string with the phrase ("He has 2 cats")

Is there a way for the program to take out the integers in the string and assign each integer to a variable?

Sharon
  • 13
  • 1
  • 2
  • It shows how to make it into an array but I want to make each integer into a variable. However, it looks almost like what I want. – Sharon Nov 05 '20 at 16:44
  • 1
    The thought of putting things into different variables usually is a beginner's mistake. Unless the structure of the text is always the same and therefore determinable, an array is the better way to achieve this. And the examples can easily be adjusted for variables btw. – maio290 Nov 05 '20 at 16:48
  • 1
    @Sharon: what if there are 12 numbers in the string? Will you have 12 variables? – Joachim Sauer Nov 05 '20 at 16:49
  • 2
    It's not possible to declare/assign an arbitrary number of variables based on a runtime input. However, you can add each found integer to an array or a Collection, which will allow you to access each one individually. – user1717259 Nov 05 '20 at 16:50
  • @Joachim Sauer Yes – Sharon Nov 05 '20 at 17:06
  • @Sharon: so what happens once you've written your code and someone calls the method with a string that contains 13 methods? What is supposed to happen in that case? – Joachim Sauer Nov 05 '20 at 19:31

2 Answers2

3

Something like this should work.

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

public class RegexExamples {
    public static void main(String[]args) {
        Pattern p = Pattern.compile("\\d+");
        Matcher m = p.matcher("He has 2 cats");
        List<Integer> numbers = new ArrayList<Integer>();
        while(m.find()) {
            numbers.add(Integer.parseInt(m.group()));
        }
    }
}
1

I think the most variable-like way to handle this would be to parse out the Integers and put them into a Map.

Something like this, note that it might break on certain unexpected inputs. If you have any question on a certain part of this code feel free to ask:

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {

    public static void main(String[] args) {
        String input = "He has 2 dogs, 5 cats, wait.. make that 6 cats, and 1000 mice!";
        Map<String, Integer> map = parseNounCounts(input);
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            System.out.println(entry.getKey() + " : " + entry.getValue());
        }
    }

    private static final Pattern NOUN_COUNT_PATTERN = Pattern.compile("(?:^|\\s)(\\d+)\\s+([a-zA-Z]*)");

    /**
     * Parses integers, and the words they precede, from the given input string and returns the map of
     * words to their preceding integer count in order of discovery.
     */
    public static LinkedHashMap<String, Integer> parseNounCounts(String input) {
        Matcher matcher = NOUN_COUNT_PATTERN.matcher(input);
        LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
        while (matcher.find()) {
            String key = matcher.group(2);
            int value = Integer.parseInt(matcher.group(1));
            if (map.containsKey(key)) {
                String newKey;
                for (int i = 2; map.containsKey(newKey = key + '#' + String.valueOf(i)); i++)
                    ;
                key = newKey;
            }
            map.put(key, value);
        }
        return map;
    }
}

Running main prints the following:

dogs : 2
cats : 5
cats#2 : 6
mice : 1000

xtratic
  • 4,600
  • 2
  • 14
  • 32