【Java学习】递归去除字符串中间空格(10)

字符串两边有空格则可以用str.trim()去除
但中间有空格怎么去除?

方法一:遇到空格跳过

package com.jingfei.csdn;

public class Demo1 {
    //去除字符串中的空格
    public static void main(String[] args) {
        String str = "hello world  !  123  我爱 你 ";
        String str1="";//定义一个空串
        for (int i = 0; i < str.length(); i++) {
            if(str.charAt(i)==' '){
                continue;
            }else{
                str1+=str.charAt(i);
            }
        }
        //System.out.println(str);
        System.out.println(str1);

    }
}

hello world  !  123  我爱 你 
helloworld!123我爱你

Process finished with exit code 0

方法二:replace

package com.jingfei.csdn;

public class Demo1 {
    //去除字符串中的空格
    public static void main(String[] args) {
        String str = "hello world  !  123  我爱 你 ";
        System.out.println(str);
        String replace = str.replace(" ", "");
        System.out.println(replace);
    }
}

hello world  !  123  我爱 你 
helloworld!123我爱你

Process finished with exit code 0

repalce方法是将里面的所有小串替换为你给定的.
当然也可以用循环,str.indexOf(’ ')=-1跳出


方法三:递归

写着玩,锻炼递归思维

package com.jingfei.csdn;

public class DemoDiGui {
    public static void main(String[] args) {
        String str = "    hello world  !  123  我爱 你";
        System.out.println(str);
        String s = strDemo(str);
        System.out.println(s);
    }
    private static String strDemo(String str) {
        if(str.indexOf(" ")==-1){
            //当str中无空格时(即==-1)返回最后一段的str
            return str;
        }else {
            //return str.substring(0,str.indexOf(" "))+strDemo(str.substring(str.indexOf(" ")).trim());
            return str.substring(0,str.indexOf(" ")).concat(strDemo(str.substring(str.indexOf(" ")).trim()));
            //前一段无空格的字符串拼上,对后一段含有空格的字符串先trim()去空格后传入方法递归
            //用concat拼接效率好一点,结果都一样
        }
    }
}

    hello world  !  123  我爱 你
helloworld!123我爱你

Process finished with exit code 0


谢谢!

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值