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);
    }
}
上一篇:阿里云ECS服务器Ubuntu安装MySQL并远程访问


下一篇:leetcode 451 根据字符出现频率排序