String练习题

 题目一

任务:将字符串中间的字符(除头尾外的其他字符)反转,

如"abc123"中的bc12反转再拼接a3,变成 a21cb3

public class work {
    public static void main(String[] args) {
        String  str = "abc123";
        reverse(str,1, str.length()-1);
    }
    public static void reverse(String str,int startIndex,int endIndex){
        // 切割字符串指定的位置
        String a1 = str.substring(startIndex, endIndex);
        // 转换成StringBuilder类型方便字符串反转
        StringBuilder sb = new StringBuilder(a1);
        // 再将反转后的StringBuilder转换成String,方便字符串拼接
        sb.reverse();
        // 拼接一头一尾
        sb.insert(0, str.substring(0, startIndex));
        str = sb.insert(sb.length(), str.charAt(endIndex)).toString();
        System.out.println(str);// a21cb3
    }
}

题目二

判断一个字符串在另一个字符串中出现的次数

public class Work02 {
    public static void main(String[] args) {
        String mainStr = "dsfadswesfsdfasfdsf";
        String subStr = "sf";
        System.out.println(compare(mainStr,subStr));
    }
    public static int compare(String mainStr,String subStr){
        int mainLength = mainStr.length();
        int subLength = subStr.length();
        // 记录查询的次数
        int count = 0;
        // 记录查询到的位置
        int index = 0;
        if (mainStr != null || subStr != null){
            if (mainLength >= subLength){
                while ((index = mainStr.indexOf(subStr, index)) != -1){
                    count++;
                    // 往查询到的字符串后面查询
                    index += subLength;
                }
            return count;
            }else {
                return 0;
            }
        }else {
            return 0;
        }
    }
}

题目三

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值