模拟实现String类中trim()的方法

@TOC模拟String类中trim()方法

个人写法

今天在学习的过程中,有一道题目的要求就是模拟trim()的方法,来实现字符串两端空格的剔除。
下面是我的写法。
本人没有百度、完全凭借自己的想法写的,在我看来,自己写的还是很复杂的,我认为是我的知识点相对薄弱,能力有限,有待提升。

//模拟trim方法,去除字符串两端的空格
public class TrimTest {
    public static void main(String[] args) {
        String str = "Ab c d e f ";
        String newStr = trimMode(str);
        System.out.println(newStr);
        System.out.println(str.trim());
    }

    public static String trimMode(String str) {
        char[] chars = str.toCharArray();
        char[] chars1 = new char[str.length() - 1];//两端只有一个空格
        char[] chars2 = new char[str.length() - 2];//两端都有空格
        if (chars[0] != ' ' && chars[chars.length - 1] != ' ') {//没有空格
            return str;
        } else if (chars[0] == ' ' && chars[chars.length - 1] != ' ') {//第一个字符为空格
            for (int i = 1; i < chars.length; i++) {
                chars1[i - 1] = chars[i];
            }
            return new String(chars1);

        } else if (chars[0] != ' ' && chars[chars.length - 1] == ' ') {//最后一个字符为空格
            for (int i = 0; i < chars.length - 1; i++) {
                chars1[i] = chars[i];
            }
            return new String(chars1);
        } else if (chars[0] == ' ' && chars[chars.length - 1] == ' ') {//都有空格
            for (int i = 1; i < chars.length - 1; i++) {
                chars2[i-1] = chars[i];
            }
            return new String(chars2);

        }
        return null;
    }
}

在实现功能后。我去看源码,发现源码写的超级简单,真的很佩服!
相比较而言,我的就挺复杂了。

public String trim() {
        int len = value.length;
        int st = 0;
        char[] val = value;    /* avoid getfield opcode */

        while ((st < len) && (val[st] <= ' ')) {
            st++;
        }
        while ((st < len) && (val[len - 1] <= ' ')) {
            len--;
        }
        return ((st > 0) || (len < value.length)) ? substring(st, len) : this;
    }

每天进步一点点,加油!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老大学Java

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值