0

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.

Muizz Mahdy
  • 798
  • 2
  • 8
  • 24

2 Answers2

2

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(" +");
clstrfsck
  • 14,715
  • 4
  • 44
  • 59
1

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

iamdeowanshi
  • 1,039
  • 11
  • 19