esmith08734
esmith08734

Reputation: 33

Parsing String to Integers

I am having trouble with my Constructor. I am passing in a String and I am suppose to get the Integer values of said String.

The String looks like [a2, a3][a4, a6][a10, a22]

I want to get rid of the a's, first, which I have done, but I am struggling with converting the 2, 3, 4, 6, 10, 22, etc into Integers. My guess would be to loop through the String and parse out the data that isn't a comma, or a [, or ] but I am fumbling through the conversion. This is what I have thus far.

public Converter(String str) {
     String getRidOfAPrefix = str.replaceAll("a", "");
     for (int i = 0; i < getRidOfAPrefix.length(); i++) {
         char charactersOfString = getRidOfAPrefix.charAt(i);
         if (charactersOfString == '[') {
           // A bit lost here

I would appreciate any tips. I have been struggling with this for hours.

Upvotes: 1

Views: 73

Answers (3)

Raudbjorn
Raudbjorn

Reputation: 480

Try something like this:

String str = "[a2, a3][a4, a6][a10, a22]";
List<Integer> result = new ArrayList<>();
str = str.replaceAll("\\]\\[", ", ").replaceAll("\\[", "").replaceAll("\\]", "").replaceAll("a", "");
Arrays.asList(str.split(", ")).forEach(num -> result.add(Integer.parseInt(num)));
System.out.println(result); //[2, 3, 4, 6, 10, 22]

Upvotes: 0

leonz
leonz

Reputation: 1127

Here's a way, but I would call it a hack. Just be careful how you use it.

You can remove closing braces and the spaces, since they're only in our way. After that we have something like "[2,3[4,6[10,22". As you can see, each number has only one delimiter now. Therefore, we can just use split method for both "[" and ",".

public Converter(String str) {
   String getRidOfAPrefix = str.replaceAll("a| |\\]", "");
   String[] nums = getRidOfAPrefix.split("\\[|,");
   for (String s: nums) {
       // do your thing
   }
}

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201447

Option 1, split on ][ and then , and then use a regular expression to replace all non-digits. Like,

String str = "[a2, a3][a4, a6][a10, a22]";
for (String x : str.split("\\]\\[")) {
    for (String s : x.split("\\s*,\\s*")) {
        System.out.println(s.replaceAll("\\D", ""));
    }
}

Option 2, use a Pattern to find everything that matches a followed by digits. Then use a loop to get all the matches, take the substring from the second character (to skip the a). Like,

Pattern p = Pattern.compile("a\\d+");
Matcher m = p.matcher(str);
while (m.find()) {
    System.out.println(m.group().substring(1));
}

Both options output

2
3
4
6
10
22

Upvotes: 2

Related Questions