Java SE常用类 - String 练习

Java SE常用类 - String 练习,第1张

Java SE常用类 - String 练习 将一个字符串进行反转。将字符串中指定部分进行反转。比如“abcdefg”反转为”abfedcg”
package com.nuo.testString;


public class testString_10_2 {
    public static void main(String[] args) {
        System.out.println(Method_String_10_2.Method_String_10_2_1(1, 3, "xiao"));
        System.out.println(Method_String_10_2.Method_String_10_2_1(2, 6, "abcdefg"));
        System.out.println(Method_String_10_2.Method_String_10_2_2(1, 3, "xiao"));
        System.out.println(Method_String_10_2.Method_String_10_2_2(2, 6, "abcdefg"));
    }
}

class Method_String_10_2{
    public static String Method_String_10_2_1(int start, int end,String str){
        if (str != null && str.length() != 0){
            int j = start;
            int k = end;
            char[] ch = str.toCharArray();
            for (int i = start; i < ((j + k) / 2 ); i++) {
                char ch_ = ch[start];
                ch[start] = ch[end - 1];
                ch[end - 1] = ch_;
                start ++;
                end --;
            }
            return new String(ch);
        }else {
            return null;
        }
    }

    public static String Method_String_10_2_2(int start, int end,String str){
        if (str != null && str.length() != 0){
//            StringBuilder str_ = new StringBuilder(str.length());
//            str_.append(str.substring(0,start));
//
//            str_.append(new StringBuilder(str.substring(start,end)).reverse());
            for (int i = end - 1; i > start - 1; i--) {
                str_.append(str.charAt(i));
            }
//            str_.append(str.substring(end,str.length()));
//            return str_.toString();
            
            return str.substring(0,start) + new StringBuilder(str.substring(start,end)).reverse() + str.substring(end,str.length());
        }else {
            return null;
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5659155.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存