Ujjawal Anand
Ujjawal Anand

Reputation: 43

Not getting expected output from java String split method

I have a string say, "1.0+20*30.2-4.0/10.1" which I want to split in such a way that I will have a string array say

strArr = {"1.0", "20", "30.2", "4.0",10.1}

I wrote the following code for this

public class StringSplitDemo {
public static void main(String[] args) {
    String str = "1.0+20*30.2-4.0/10.1";
    String[] strArr = (str.split("[\\+-/\\*]"));
    for(int i=0;i<strArr.length;i++)
      System.out.print(strArr[i]+" ");
  }
}

Rather than printing the expected output(by me) i.e 1.0 20 30.2 4.0 10.1 it prints

output: 1 0 20 30 2 4 0 10 1 

which seems to split the string also around "." even if I didn't include it in the regex pattern.

What I'm missing here? What is the right way to do this?

Upvotes: 1

Views: 59

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626825

Use

String str = "1.0+20*30.2-4.0/10.1";
String[] strArr = str.split("[-+/*]");
System.out.print(Arrays.toString(strArr));

See the online Java demo

The [\\+-/\\*] character class matches more than just the 4 chars you defined, as - created a range between + and /.

enter image description here

You could fix the regex by escaping the hyphen, but the pattern looks much cleaner when you put the - at the start (or end) of the character class, where you do not have to escape it as there, the hyphen is treated as a literal -.

Upvotes: 1

Naruto
Naruto

Reputation: 4329

The issue was in regex

So you need to escape + otherwise it will treat it as atleast once

String[] strArr = (str.split("[\\-/\\*\\+]"));

By the way escape symbol here is not required. It can simply be written as

String[] strArr = (str.split("[-/*+]"));

Upvotes: 0

Related Questions