简体   繁体   中英

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. 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. 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) . 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. You are using the char type, and that's why you can't specify a "nothing" 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 :

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:

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:

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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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