栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

模拟一个Java中String类的trim()方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

模拟一个Java中String类的trim()方法

我的实现思路:

使用到双指针,从字符串的两边(开始和结尾)往中间走,直到找到不为空格的索引位置就停下来。然后将剩余的部分进行遍历。

代码演示:

public class TrimSimulate {

    public static void main(String[] args) {
        String s = trimSimulate("    sdfsdfss             sdf     ");
        System.out.println(s);
    }


    public static String trimSimulate(String str) {

        String targetStr = "";

        int i = 0,j = str.length() - 1;

        int start = 0;
        int end = 0;

        while (i < j){
            String currentValuei = String.valueOf(str.charAt(i));
            String currentValuej = String.valueOf(str.charAt(j));
            if (currentValuei.contains(" ")){
                i++;
            }else if (currentValuej.contains(" ")){
                j--;
            }else {
                start = i;
                end = j;
                break;
            }
        }

        for (int k = start; k <= end; k++) {
            targetStr += str.charAt(k);
        }


        return targetStr;
    }
}

结果:

优化:

//去掉首尾空格,优化
    public static String trimSimulate1(String str) {
        String targetStr = "";

        int start = 0 , end = str.length() -1;
        while (start < end){

            if (str.charAt(start) == ' '){
                start++;
            }else if (str.charAt(end) == ' '){
                end--;
            }else {
                break;
            }
        }

        for (int i = start; i <= end; i++) {
            targetStr += str.charAt(i);
        }

//        或者使用String的内部方法截取
//        String substring = str.substring(start, end+1);

        return targetStr;
    }

不足之处请指正~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/991825.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号