0

There is something that I want to know. I have homework where they want us to take two string input in polynomial form, and there is lots of implementation. Here my question: when I take the input from the user, I can split the string into polynomial parts but it goes wrong:

The string: "-x^3 - 6x^2 + 4x + 22"

I want to split this like:

-x^3                      
- 6x^2 
+ 4x 
+ 22

but it prints

package splitmethod;
import java.util.Scanner;
import java.io.*;

public class uygulama {

  public static void main(String args[]){


      System.out.println("lütfen parçalmak istidigniz polinomu girniz ");

      Scanner input= new Scanner(System.in);

      String polinom= input.nextLine();

      String[] result;

      System.out.println("");

      result=polinom.replaceAll("\\s+","").split("(?<=[+-])");

      for(int i=0;i<result.length;i++){

          System.out.println(result[i]);
Rook
  • 5,734
  • 3
  • 34
  • 43
SNYLMZ
  • 25
  • 1
  • 9

4 Answers4

1

(?<=[+-]) means to split on place which has + or - before it. So for data like -x^3-6x^2+4x+22 you are splitting here (I will mark this place with |)

-|x^3-|6x^2+|4x+|22

What you want is to split on place which has + or - after it (and don't split on - or + placed at start of entire string). So instead of look-behind (?<=...) you need to use look-ahead (?=...).

Example: |-x^3|-6x^2|+4x|+22 where | represents place to split. As you see I also placed | at start of string because it has + or - after it.

So try to use split("(?=[+-])")

If you are using Java 8 you will get correct results because for zero-length (or zero-width) regex matches (like the one from look-around mechanism), empty strings at start of result arrays are removed so you will not end up with ["", "-x^3", "-6x^2", "+4x", "+22"] array but
["-x^3", "-6x^2", "+4x", "+22"].

If you are using earlier version of Java you will need to add condition to prevent matching this first | before -x^3 element. You can do it by adding (?<!^) to your regex to make sure that place of match (in your case place of split) is not right after start of string (represented by ^):

So in pre Java 8 versions use split("(?=[+-])(?<!^)")


Other way to avoid empty string which could be returned because of splitting on - at start of String is to use another instance of Scanner class with delimiter (?=[+-]) which will "parse" input from user, so your code could look like

String polinom = "-x^3 - 6x^2 + 4x + 22";//here you pass data from user

Scanner scanner = new Scanner(polinom);
scanner.useDelimiter("(?=[+-])");

while (scanner.hasNext())
    System.out.println(scanner.next());

scanner.close();

Output:

-x^3 
- 6x^2 
+ 4x 
+ 22
Community
  • 1
  • 1
Pshemo
  • 122,468
  • 25
  • 185
  • 269
0

I don't actually think you need to use regex. Just iterate through the String would be enough and check for +/- would be enough. Something like:

StringBuilder sb = new StringBuilder();
for(int i=0;i<polinom.length;i++) {
    if(i!=0 && (polinom.charAt(i)=='-' || polinom.charAt(i)=='+')) {
        System.out.println(sb.toString());
        sb = new StringBuilder();
        sb.append(polinom.charAt(i));
    } else {
        sb.append(polinom.charAt(i));
    }
}
System.out.println(sb.toString());

So basically you buffer polinom and whenever you meet + or - you know that one term in the polynomial has ended. So you print the buffer and start a new buffer.

zyl1024
  • 690
  • 1
  • 9
  • 23
0

The regexp "(?<=[+-])" is "positive lookbehind". This means that it will split after the + or -. You need "positive lookahead", "(?=[+-])".

But anyway, as you're removing the spaces before doing this, you'll get your + and - without any space between them and the operands,

-x^3
+6x^2
+4x
+22

which is not what you said you wanted. Personally, for the sake of parsing infix operations I would go with splitting by the white spaces, so that the operators are separate from the actual terms.

RealSkeptic
  • 33,993
  • 7
  • 53
  • 79
0
import java.util.Scanner;
public class uygulama {
    public static void main(String args[]) {


      System.out.println("lütfen parçalmak istidigniz polinomu girniz ");

      Scanner input= new Scanner(System.in);

      String polinom= input.nextLine();

      String[] result;

      System.out.println("");

      result = polinom.split(" "); //just splits the words by space so the signs in front are not stored in the same array as the addressed variable/coefficient combo

      for(int i=0;i<result.length;i++){

          System.out.println(result[i]);
      }

    }

}
ljeabmreosn
  • 169
  • 8