编程语言
首页 > 编程语言> > Java模拟 trim 方法,去除字符串两端空格

Java模拟 trim 方法,去除字符串两端空格

作者:互联网

public class StringDemo1 {
    @Test
    public void show() {
        String s1 = "   hello world   sss    ";
        String s2 = myTrim(s1);
        System.out.println(s2); //=> hello world   sss
    }

    public String myTrim(String str) {
        char[] chars = str.toCharArray();
        int leftIndex = 0;
        int rightIndex = 0;
        // 先获取最左边不是空格的下标
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ' ') {
                leftIndex = i;
                break;
            }
        }
        // 在获取最右边不是空格的下标
        for (int i = chars.length - 1; i >= 0; i--) {
            if (chars[i] != ' ') {
                rightIndex = i;
                break;
            }
        }
        return str.substring(leftIndex, rightIndex + 1);
    }
}

标签:trim,Java,String,int,chars,空格,rightIndex,leftIndex,public
来源: https://www.cnblogs.com/songzxblog/p/15093920.html