0

I have String containing zeros, ones and unfortunately a lot of white spaces. I want to write method which will get rid of all the white spaces and return String with just ones and zeros.

How can I do that?

String example= new String("1 011 01   1");

String shouldReturnStringWithoutWhiteSpaces(String given){
    String cleanString
    //some action which will "transform "1 011 01   1" into "1011011"
    return cleanString;
}
MaciejF
  • 516
  • 1
  • 6
  • 16

4 Answers4

5

You can do

String cleanString = given.replaceAll("\\s", "");

This will replace all whitespace with nothing. The main trick is the \\s which becomes \s at runtime which means all white spaces.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

Use Scanner on your string with default delimiter. Add anything you find to a new string

string result = "";

Scanner scan = new Scanner(example);

while(scan.hasNext())
    result += scan.next();
gkrls
  • 2,618
  • 2
  • 15
  • 29
0

You can do something like that

 String res = given.replace(" ", "");

or

String res = given.replaceAll("\\s", "");

First one is replace(CharSequence target, CharSequence replacement;)

Second one is replaceAll(String regex, String replacement);

More about differences between CharSequence and String is here. If you want yout function String shouldReturnStringWithoutWhiteSpaces(String given) to return String, you should use second one ;)

Community
  • 1
  • 1
dawidklos
  • 902
  • 1
  • 9
  • 32
-1

String something = given.replaceAll(" +", "")

Chrispresso
  • 3,660
  • 2
  • 19
  • 31