将字符串中指定部分进行反转,比如“abcdefg”反转为”abfedcg”

import java.util.Scanner;

/**
 * @author 
 * @date 2021/3/5 19:05
 * 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反
 * 转为”abfedcg”
 */
public class StringOrder {
    private static int CHAR_LEN=10;
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入字符串");
        String str=scanner.next();
        char[] chars=new char[CHAR_LEN];
//        截取需要替换的区间
        System.out.println("请输入起始区间");
//        开始区间
        int start=scanner.nextInt();
//        结束区间
        int end=scanner.nextInt();
//        头部字符串用于拼接
        String strhead=str.substring(0,start);
//        中部待替换字符串
        String strreplace=str.substring(start,end+1);
//        尾部拼接字符串
        String strtail=str.substring(end+1,str.length());
//        将区间内的字符串转换为字符
        strreplace.getChars(0,strreplace.length(),chars,0);
//        调用逆序方法,进行字符的逆序
        replacechar(chars,end-start);
//        将逆序的字符转换为字符串
        String newstr=new String(chars,0,(end-start)+1);
//        替换原来的正序字符串,并输出
//        System.out.println(str.replace(replacestr,newstr));//无重复字符可用
        String strend=strhead+newstr+strtail;
        System.out.println(strend);


    }
    public static void replacechar(char[] chars,int len){
        char n;
        for (int i = 0, j =len; i<chars.length/2; i++){
            if (i<=j){
                n=chars[i];
                chars[i]=chars[j];
                chars[j]=n;
                j--;
            }else break;
        }
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值