Muizz Mahdy
Muizz Mahdy

Reputation: 808

Extracting signs/symbols from a string in Java

I have a string with signs and i want to get the signs only and put them in a string array, here is what I've done:

String str = "155+40-5+6";

// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]", " ");

// then get an array that contains the signs without spaces
String[] signsArray = stringSigns.trim().split(" ");

However the the 2nd element of the signsArray is a space, [+ , , -, +]

Thank you for your time.

Upvotes: 0

Views: 810

Answers (2)

iamdeowanshi
iamdeowanshi

Reputation: 1069

Just replace " " to "" in your code

String str = "155+40-5+6";

// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]","");

// then get an array that contains the signs without spaces
String[] signsArray = stringSigns.split("");

This should work for you. Cheers

Image of running code enter image description here

Upvotes: 1

clstrfsck
clstrfsck

Reputation: 14829

You could do this a couple of ways. Either replace multiple adjacent digits with a single space:

// replace the numbers with spaces, leaving the signs and spaces
String signString = str.replaceAll("[0-9]+", " ");

Or alternatively in the last step, split on multiple spaces:

// then get an array that contains the signs without spaces
String[] signsArray = signString.trim().split(" +");

Upvotes: 2

Related Questions