-2

I have an input that recieves a String in java:

"a                                                a" 

(50 characters total, 2 letters and 48 whitespaces)

when i tried

replace("\\s++","");

or

replaceAll("\\s+","");

removes the whitespaces, but keeps on the string(char array) with '\u0000' 0 How i remove this to make the string only with 2 characters?

YCF_L
  • 51,266
  • 13
  • 85
  • 129
  • 2
    See http://stackoverflow.com/questions/28989970/java-removing-u0000-from-an-string. – rjsperes May 06 '17 at 15:15
  • Which char array are you talking about? What is the complete code? And why are you using a regexpt when you could simply use `replace(" ", "")`? – JB Nizet May 06 '17 at 15:16
  • did you expect `a only one space a` like `a a` or what exactly? – YCF_L May 06 '17 at 15:17
  • why do you replace and dont filter the character? where are the whitespaces: at the begining, between the characters, at the end, ...? – Kevin Wallis May 06 '17 at 15:17
  • @rperes solution worked. I was tyring to change the string i have to make smaller, but thanks for all help and tips! – Luiz Andrade May 06 '17 at 15:59
  • When you say "2 letters and 48 whitespaces" do you assume that `\u0000` is one of whitespaces? If yes then this is cause of your problem since `\u0000` isn't considered as whitespace so you need to handle it separately. You can check it with `Character.isWhitespace('\u0000')` which returns `false`. – Pshemo May 06 '17 at 17:04

2 Answers2

1

First, I would remind you to keep in mind that the function replaceAll returns a new string and does not change the original. Strings in Java are immutable.

Then for removing whitespaces and '\u0000' just do this:

    String a = "a                                                a" ;
    a = a.replaceAll("[\\s\u0000]+","");   // set the result to a;
    System.out.println(a + " " + a.length());

OUTPUT:

aa 2
Community
  • 1
  • 1
granmirupa
  • 2,738
  • 15
  • 27
-1
   String str = "a                                                a" ;

   str = str.replaceAll(" ", "");
    System.out.println(str);
Michael Grinnell
  • 872
  • 1
  • 11
  • 30