Rach
Rach

Reputation: 167

How to rid of extra spaces in array list Java

When I try to break up a string such as 10-5*6/2+20 to leave just the operators in a array list, it adds an extra two places at the start of my array list.

Why is this happening and how can I prevent it?

The more digits for the starting number, the more empty spaces added to the start of the list.

String sum = "10-5*6/2+20";
String numbers = "[\\d]"; 
String string = sum;
String[] splits = string.split(numbers);

for (int i = 0; i <  splits.length; i++)
{                   
    System.out.println(splits[i]);
}

Upvotes: 1

Views: 434

Answers (1)

assylias
assylias

Reputation: 328598

You could use a Matcher and retrieve what you are interested in, instead of removing what you don't want:

String sum = "10-5*6/2+20";
Matcher m = Pattern.compile("\\D").matcher(sum); //keep non digit characters
while (m.find()) {
  System.out.println(m.group());
}

Upvotes: 2

Related Questions