簡體   English   中英

如何從字符串中刪除所有空格?

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

我正在嘗試從字符串中刪除所有空格。 我用谷歌搜索了很多,發現只有replaceAll()方法用於刪除空格。 但是,在我為在線課程做的作業中,它說使用replace()方法刪除所有空格並使用\\n表示換行符,使用\\t表示制表符。 我試過了,這是我的代碼:

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

編譯后,我收到錯誤消息:

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

所有 3 都指的是public static String removeWhitespace(String s)的上述replace()代碼。 如果有人指出我做錯了什么,我將不勝感激。

replace()有兩種風格 - 一種采用字符,一種采用字符串。 您正在使用 char 類型,這就是您不能指定“無”字符的原因。

使用字符串版本:

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

還要注意我在那里更正的錯誤:您的代碼一遍又一遍地替換原始字符串中的字符,因此只會影響最后一次替換。


你可以只編碼這個:

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

試試這個代碼,

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

輸出 :

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

另一種使用 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;
    }
}

輸出 :

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

如果你想為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');
}

但是空字符仍然是字符,因此最好為replace(CharSequence,CharSequence)方法指定一個空字符串以刪除這些字符:

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

為了簡化此代碼,您可以為replaceAll(String,String)方法指定一個正則表達式以刪除所有空白字符

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

也可以看看:
替換字符串中的特殊字符
使用 LinkedHashMap 的字符串中的第一個唯一字符

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM