0

I have a String in the format first<-0 or i<-length where the <- is used instead of the assignment operator.

I want to break it in 3 parts i.e. left side, operator and right side.

Then store all 3 parts after tokenization.

The problem isn't storing the delimeters, I have already solved that by passing the 3rd parameter true in constructor.

The issue is that the StringTokenizer only works when the delimeter is 1 character long. Any work around this?

    StringTokenizer tokens= new StringTokenizer("first<-0", "<-", true);
abdulwasey20
  • 747
  • 8
  • 21

1 Answers1

0

You can do it as follows:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {

        String str = "first<-0";

        // Without using regex
        String[] parts = new String[3];
        parts[0] = str.substring(0, str.indexOf("<-"));
        parts[1] = "<-";
        parts[2] = str.substring(str.indexOf("<-") + 2);
        System.out.println(Arrays.toString(parts));

        // Using regex
        String[] p = str.split("((?<=<-)|(?=<-))");
        System.out.println(Arrays.toString(p));
    }
}

Output:

[first, <-, 0]
[first, <-, 0]

Feel free to comment in case of any doubt.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110