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+"---");
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值