1
String output = new String(encryptText);
output = output.replaceAll("\\s", "");
return output;

replaceAll("\\s", ""); doesn't work

Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
sdfasdfw
  • 13
  • 1
  • 1
  • 4
  • 1
    your code seems to be fine. it should work. I would check what encryptText looks like – gefei Apr 11 '13 at 07:35
  • could you please share the input string? because str.replaceAll("\\s", ""); should work. You can also try str.replaceAll(" ", ""); – Abhinaba Basu Apr 11 '13 at 07:36
  • You should add the error you get or an example of why the solution you posted doesn't work or your question seems to be a duplicate of this one: http://stackoverflow.com/questions/5455794/removing-whitespace-from-strings-in-java – Luigi Massa Gallerano Apr 11 '13 at 07:36

6 Answers6

2
String output = new String(encryptText);
output = output.replaceAll(" ", "");
return output;
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
  • We have to say that this solution works only for "pure" whitespace characters. It doesn't catch "special" whitespace characters like tab (\t). Instead, the solution based on java.util.regex.Pattern: replaceAll("\\s", "") does work for every whitespace character: [ \t\n\x0B\f\r] – Luigi Massa Gallerano Apr 11 '13 at 08:24
1

I was facing the same problem then I searched a lot and found that, it is not a space character but a null value which is transformed into string from character array. This resolved the issue for me -

output.replaceAll(String.valueOf((char) 0), "");
Aakash Mangal
  • 125
  • 3
  • 12
0

Your code works fine for me, see here

Anyway you can use the StringUtils.trimAllWhitespace from the spring framework:

output = StringUtils.trimAllWhitespace(output);
CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

You could use the non-regex-version replace to do the job:

output = output.replace(" ", "");
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33
0

Use String.replaceAll(" ","") or if you want to do it yourself without a lib call, use this.

        String encryptedString = "The quick brown fox ";
        char[] charArray = encryptedString.toCharArray();
        char [] copy = new char[charArray.length];
        int counter = 0;
        for (char c : charArray)
        {
            if(c != ' ')
            {
                copy[counter] = c;
                counter++;
            }
        }
        char[] result = Arrays.copyOf(copy, counter);
        System.out.println(new String(result));
Deepak Bala
  • 11,095
  • 2
  • 38
  • 49
0
z = z.replaceAll(" ", "");

easiest and the simplest way for removing white spaces from the char [];

Procrastinator
  • 2,526
  • 30
  • 27
  • 36