Removing whitespace from strings in Java

前端 未结 30 1842
一个人的身影
一个人的身影 2020-11-22 05:01

I have a string like this:

mysz = \"name=john age=13 year=2001\";

I want to remove the whitespaces in the string. I tried trim()

相关标签:
30条回答
  • 2020-11-22 05:23

    Use apache string util class is better to avoid NullPointerException

    org.apache.commons.lang3.StringUtils.replace("abc def ", " ", "")
    

    Output

    abcdef
    
    0 讨论(0)
  • 2020-11-22 05:23

    Separate each group of text into its own substring and then concatenate those substrings:

    public Address(String street, String city, String state, String zip ) {
        this.street = street;
        this.city = city;
        // Now checking to make sure that state has no spaces...
        int position = state.indexOf(" ");
        if(position >=0) {
            //now putting state back together if it has spaces...
            state = state.substring(0, position) + state.substring(position + 1);  
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:25

    Using Pattern And Matcher it is more Dynamic.

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RemovingSpace {
    
        /**
         * @param args
         * Removing Space Using Matcher
         */
        public static void main(String[] args) {
            String str= "jld fdkjg jfdg ";
            String pattern="[\\s]";
            String replace="";
    
            Pattern p= Pattern.compile(pattern);
            Matcher m=p.matcher(str);
    
            str=m.replaceAll(replace);
            System.out.println(str);    
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:26
    replaceAll("\\s","")
    

    \w = Anything that is a word character

    \W = Anything that isn't a word character (including punctuation etc)

    \s = Anything that is a space character (including space, tab characters etc)

    \S = Anything that isn't a space character (including both letters and numbers, as well as punctuation etc)

    (Edit: As pointed out, you need to escape the backslash if you want \s to reach the regex engine, resulting in \\s.)

    0 讨论(0)
  • 2020-11-22 05:27

    There are others space char too exists in strings.. So space char we may need to replace from strings.

    Ex: NO-BREAK SPACE, THREE-PER-EM SPACE, PUNCTUATION SPACE

    Here is the list of space char http://jkorpela.fi/chars/spaces.html

    So we need to modify

    \u2004 us for THREE-PER-EM SPACE

    s.replaceAll("[\u0020\u2004]","")

    0 讨论(0)
  • 2020-11-22 05:29
    public static String removeWhiteSpaces(String str){
        String s = "";
        char[] arr = str.toCharArray();
        for (int i = 0; i < arr.length; i++) {
            int temp = arr[i];
            if(temp != 32 && temp != 9) { // 32 ASCII for space and 9 is for Tab
                s += arr[i];
            }
        }
        return s;
    }
    

    This might help.

    0 讨论(0)
提交回复
热议问题