简体   繁体   中英

How to Split a String without deleting split character

I would like to split a String into parts, but when the String is split the character shouldn't be deleted.

In my Example, I would like to have the Output:

parts[0]= 4x
parts[1]= -3y
parts[2]= 6z
parts[3]= 3v

This is my Code:

import java.util.Arrays;

public class Polynomaddition {

public static void main(String[] args) {
    String fraction = "4x-3y+6z+3v";
    String [] parts = fraction.split("(?<=\\[a-z]");
    System.out.println(Arrays.toString(parts));
    //String result = calculator(fraction);
}

public static String calculator(String s) {
    String result = "";
     String [] parts = s.split("(?<=[a-z])", -1);

    return result;
    }
}

Solution 1

In your cases, it seems you want this regex \\+|(?=-) :

String[] parts = fraction.split("\\+|(?=-)");

details

  • split with
  • \\+ plus sign
  • | or
  • (?=-) minus without deleting it

Solution 2

Or with your regex but you need to check each result, for example :

String[] parts = Arrays.stream(fraction.split("(?<=[a-z])"))
        .map(s -> s.startsWith("+") ? s.substring(1, s.length()) : s)
        .toArray(String[]::new);

Outputs

[4x, -3y, 6z, 3v]

I would not use split at all. Instead, use a pattern that matches the actual polynomial term, and use a Matcher, specifically its find and group methods, to extract each matched term:

List<String> parts = new ArrayList<>();

Matcher termMatcher = Pattern.compile("[-+]?\\d+[a-z]").matcher(fraction);
while (termMatcher.find()) {
    String part = termMatcher.group();
    if (part.startsWith("+")) {
        part = part.substring(1);
    }
    parts.add(part);
}

System.out.println(parts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM