简体   繁体   English

如何从字符串中删除所有空格?

[英]How do I remove all whitespaces from a string?

I'm trying to remove all whitespaces from a string.我正在尝试从字符串中删除所有空格。 I've googled a lot and found only replaceAll() method is used to remove whitespace.我用谷歌搜索了很多,发现只有replaceAll()方法用于删除空格。 However, in an assignment I'm doing for an online course, it says to use replace() method to remove all whitespaces and to use \\n for newline character and \\t for tab characters.但是,在我为在线课程做的作业中,它说使用replace()方法删除所有空格并使用\\n表示换行符,使用\\t表示制表符。 I tried it, here's my code:我试过了,这是我的代码:

public static String removeWhitespace(String s) {
    String gtg = s.replace(' ', '');
    gtg = s.replace('\t', '');
    gtg = s.replace('\n', '');
    return gtg;
}

After compiling, I get the error message:编译后,我收到错误消息:

Error:(12, 37) java: empty character literal
Error:(13, 37) java: empty character literal
Error:(14, 37) java: empty character literal

All 3 refer to the above replace() code in public static String removeWhitespace(String s) .所有 3 都指的是public static String removeWhitespace(String s)的上述replace()代码。 I'd be grateful if someone pointed out what I'm doing wrong.如果有人指出我做错了什么,我将不胜感激。

There are two flavors of replace() - one that takes chars and one that takes Strings. replace()有两种风格 - 一种采用字符,一种采用字符串。 You are using the char type, and that's why you can't specify a "nothing" char.您正在使用 char 类型,这就是您不能指定“无”字符的原因。

Use the String verison:使用字符串版本:

gtg = gtg.replace("\t", "");

Notice also the bug I corrected there: your code replaces chars from the original string over and over, so only the last replace will be effected.还要注意我在那里更正的错误:您的代码一遍又一遍地替换原始字符串中的字符,因此只会影响最后一次替换。


You could just code this instead:你可以只编码这个:

public static String removeWhitespace(String s) {
    return s.replaceAll("\\s", ""); // use regex
}

Try this code,试试这个代码,

public class Main {
    public static void main(String[] args) throws Exception {
        String s = " Test example    hello string    replace  enjoy   hh ";
        System.out.println("Original String             : "+s);
        s = s.replace(" ", "");
        System.out.println("Final String Without Spaces : "+s);
    }
}

Output :输出 :

Original String             :  Test example    hello string    replace  enjoy   hh                                                                         
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh 

Another way by using char array :另一种使用 char 数组的方法:

public class Main {
    public static void main(String[] args) throws Exception {
        String s = " Test example    hello string    replace  enjoy   hh ";
        System.out.println("Original String             : "+s);
        String ss = removeWhitespace(s);
        System.out.println("Final String Without Spaces : "+ss);
      
    } 
    
    public static String removeWhitespace(String s) {
        char[] charArray = s.toCharArray();
        String gtg = "";
        
        for(int i =0; i<charArray.length; i++){                
            if ((charArray[i] != ' ') && (charArray[i] != '\t') &&(charArray[i] != '\n')) {
                gtg = gtg + charArray[i];
            }
        }    
        return gtg;
    }
}

Output :输出 :

Original String             :  Test example    hello string    replace  enjoy   hh                                                                         
Final String Without Spaces : Testexamplehellostringreplaceenjoyhh

If you want to specify an empty character for the replace(char,char) method, you should do it like this:如果你想为replace(char,char)方法指定一个空字符,你应该这样做:

public static String removeWhitespace(String s) {
    // decimal format, or hexadecimal format
    return s.replace(' ', (char) 0)
            .replace('\f', (char) 0)
            .replace('\n', (char) 0)
            .replace('\r', '\u0000')
            .replace('\t', '\u0000');
}

But an empty character is still a character , therefore it is better to specify an empty string for the replace(CharSequence,CharSequence) method to remove those characters:但是空字符仍然是字符,因此最好为replace(CharSequence,CharSequence)方法指定一个空字符串以删除这些字符:

public static String removeWhitespace(String s) {
    return s.replace(" ", "")
            .replace("\f", "")
            .replace("\n", "")
            .replace("\r", "")
            .replace("\t", "");
}

To simplify this code, you can specify a regular expression for the replaceAll(String,String) method to remove all whitespace characters :为了简化此代码,您可以为replaceAll(String,String)方法指定一个正则表达式以删除所有空白字符

public static String removeWhitespace(String s) {
    return s.replaceAll("\\s", "");
}

See also:也可以看看:
Replacing special characters from a string 替换字符串中的特殊字符
First unique character in a string using LinkedHashMap 使用 LinkedHashMap 的字符串中的第一个唯一字符

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

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