2

Taking the string -2x^2+3x^1+6 as an example, how how to extract -2, 3 and 6 from this equation stored in the string?

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Manish
  • 53
  • 2
  • 8
  • I have tried extracting using + as a delimiter to extract -2x2 3x and 6 ..then what to do – Manish Nov 16 '12 at 11:24
  • How about running "-2x^2" through the extraction with delimiter 'x' ? (btw. do you have plans how to handle e.g. 3x^3-2x^2-3 ? – Aki Suihkonen Nov 16 '12 at 11:33

2 Answers2

10

Not giving the exact answer but some hints:

  • Use replace meyhod:

    replace all - with +-.

  • Use split method:

    // after replace effect
    String str = "+-2x^2+3x^1+6"
    String[] arr = str.split("+");
    // arr will contain: {-2x^2, 3x^1, 6}
    
  • Now, each index value can be splitted individually:

    String str2 = arr[0];
    // str2 = -2x^2;
    // split with x and get vale at index 0
    
Azodious
  • 13,752
  • 1
  • 36
  • 71
2
    String polynomial= "-2x^2+3x^1+6";
    String[] parts = polynomial.split("x\\^\\d+\\+?");
    for (String part : parts) {
        System.out.println(part);
    }

This should work. Sample output

polynomial= "-2x^2+3x^1+6"
Output:
-2
3
6 
polynomial = "-30x^6+20x^3+3"
Output:
-30
20
3
MoveFast
  • 3,011
  • 2
  • 27
  • 53
  • Thank you Manoj but this would not work in the condition if - sign comes example "-2x^2-3x^1+6" – Manish Nov 16 '12 at 11:43
  • @Manish did a small change. It should work for this case now. I have made the + sign match optional. This way negative nos will also be matched. – MoveFast Nov 16 '12 at 11:50
  • I was wondering what if the sequence is entered as 6+3x^1-2x^2 ..in this case the matching pattern will change.. – Manish Nov 17 '12 at 17:58
  • @Manish ya..then pattern will change..if that is case i think that a better approach is to first split on basis of +/- sign, and then further extract the digit from the splitted portion – MoveFast Nov 18 '12 at 09:58