0

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.

Kirby
  • 15,127
  • 10
  • 89
  • 104
Shreyash
  • 81
  • 1
  • 10

3 Answers3

3

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
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • Thanks! I will use this. Also if I have to use replace() as mentioned in the assignment, will I have to create 2 additional new strings to remove all whitespaces? – Shreyash Aug 05 '20 at 19:08
  • 1
    @Shreyash if you must use `replace()`, do this: `return s.replace(" ", "").replace("\t", "").replace("\n", "");` – Bohemian Aug 05 '20 at 22:34
1

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
Som
  • 1,522
  • 1
  • 15
  • 48
0

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