简体   繁体   English

在java中将带空格的char数组转换为String时如何删除该S​​tring中的空格?

[英]In java when converting a char array with spaces to a String how to remove the spaces in that String?

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

replaceAll("\\\\s", ""); doesn't work 不起作用

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

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), "");

Your code works fine for me, see here 你的代码对我来说很好,请看这里

Anyway you can use the StringUtils.trimAllWhitespace from the spring framework : 无论如何,你可以使用spring框架中StringUtils.trimAllWhitespace

output = StringUtils.trimAllWhitespace(output);

您可以使用非正则表达式替换来完成这项工作:

output = output.replace(" ", "");

Use String.replaceAll(" ","") or if you want to do it yourself without a lib call, use this. 使用String.replaceAll(" ","")或者如果你想在没有lib调用的情况下自己完成它,请使用它。

        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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM