Correct way to trim a string in Java

后端 未结 8 902
独厮守ぢ
独厮守ぢ 2020-12-15 04:30

In Java, I am doing this to trim a string:

String input = \" some Thing \";
System.out.println(\"before->>\"+input+\"<<-\");
input = input.trim(         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 04:44

    If we have to trim a String without using trim(), split() methods of Java then following source code can be helpful.

    static String allTrim(String str)
    {
        int j = 0;
        int count = 0;  // Number of extra spaces
        int lspaces = 0;// Number of left spaces
        char ch[] = str.toCharArray();
        int len = str.length();
        StringBuffer bchar = new StringBuffer();
        if(ch[0] == ' ')
        {
            while(ch[j] == ' ')
            {
                lspaces++;
                j++;
            }   
        }   
        for(int i = lspaces; i < len; i++)
        {   
            if(ch[i] != ' ')
            {
                if(count > 1 || count == 1)     
                {
                    bchar.append(' ');
                    count = 0;
                }
                bchar.append(ch[i]);
            }
            else if(ch[i] == ' ')
            {
                count++;    
            }
        }
        return bchar.toString();
    }
    

提交回复
热议问题