-2

I have a string like this 3x^2 I want to extract the first and the second number and store them in an array. and if they didn't exist they should be considered as 1.

EDIT : For example in string x the first and the second number are 1 or in string 3x the second number is 1. I think it should be clear now.

Nikolas Charalambidis
  • 35,162
  • 12
  • 84
  • 155
Mohammad Sianaki
  • 1,035
  • 9
  • 14

2 Answers2

1

if the numbers are allways separated by x^, just split the string using this separator

String[] splitted = "3x^2".split("x\\^");
Raphael Roth
  • 25,362
  • 13
  • 78
  • 128
1

Just get digits with the Regex:

String str = "3x^2";
String pattern = "(\\d+)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(str);
ArrayList<Integer> numbers = new ArrayList<>();

Find with Matcher all numbers and add them to the ArrayList. Don't forget to convert them to int, because m.group() returns the String.

while (m.find()) {
   numbers.add(Integer.parseInt(m.group()));
}

And if your formula doesn't contain the second number, add there your desired default item.

if (numbers.size<2) {
   numbers.add(1);
}

Finally print it out with:

for (int i: numbers) {
   System.out.print(i + " ");
}

And the output for 3x^2 is 3 2.

And for the 8x it is 8 1.

Nikolas Charalambidis
  • 35,162
  • 12
  • 84
  • 155