Java中模拟一 个 trim 方法,去除字符串两端的空格 。

1.解题思路:

  1. 首先使用一个start索引记录字符串从前往后的空格索引,使用end索引记录字符串从后往前的空格索引。

  2. 然后将这个字符串转换为char类型的数组,遍历这个数组,如果从前往后,有空格start就加1,从后往前如果有空格,end就减一。

  3. 使用subString()的方法,截取[start,end+1)之间的字符串就可以了。

2.代码实现:

public class AITest1 {

    public String myTrim(String str) {
        //模拟一个trim方法,去除字符串两端的空格
        if (str != null) {
            int start = 0;//用于记录从前往后首次索引位置不是空格的位置索引

            int end = str.length() - 1;//用于记录从后往前首次索引位置不是空格的位置索引

            while (start < end && str.charAt(start) == ' ') {
                start++;
            }
            while (start < end && str.charAt(end) == ' ') {
                end--;
            }

            if (str.charAt(start) == ' ') {
                return "";
            }

            return str.substring(start, end + 1);
        }

        return null;
    }

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        //获取用户输入的字符串
        String str = null;
        System.out.println("请输入任意字符:");
        str = scanner.nextLine();
        System.out.println("您输入的字符为:-----" + str + "-----");

        AITest1 aiTest1 = new AITest1();
        String s = aiTest1.myTrim(str);
        System.out.println("---"+s+"---");
    }
}


版权声明:本文为weixin_43990532原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。