zoukankan      html  css  js  c++  java
  • 字符串部分翻转

    package com.learning.java;
    
    import org.junit.Test;
    
    public class StringDemo {
    
        //方式一:转换为char[]
        public String reverse(String str, int startIndex, int endIndex) {
            if (str != null) {
                char[] arr = str.toCharArray();
                for (int x = startIndex, y = endIndex; x < y; x++, y--) {
                    char temp = arr[x];
                    arr[x] = arr[y];
                    arr[y] = temp;
                }
                return new String(arr);
            }
            return null;
        }
    
        //方式二:使用String的拼接
        public String reverse1(String str, int startIndex, int endIndex) {
            if (str != null) {
                String reverseStr = str.substring(0, startIndex);
    
                for (int i = endIndex; i >= startIndex; i--) {
                    reverseStr += str.charAt(i);
                }
                reverseStr += str.substring(endIndex + 1, str.length());
                return reverseStr;
            }
            return null;
        }
    
        //方式三:使用StringBuffer/StringBuilder替换String
        public String reverse2(String str, int startIndex, int endIndex) {
            if (str != null) {
                StringBuilder builder = new StringBuilder(str.length());
                builder.append(str.substring(0, startIndex));
                for (int i = endIndex; i >= startIndex; i--) {
                    builder.append(str.charAt(i));
                }
                builder.append(str.substring(endIndex + 1));
                return builder.toString();
            }
            return null;
        }
    
        @Test
        public void test1() {
            String str = "abcdefg";
            String str1 = reverse(str, 2, 5);
            String str2 = reverse1(str, 2, 5);
            String str3 = reverse2(str, 2, 5);
    
            System.out.println(str1);
            System.out.println(str2);
            System.out.println(str3);
    
        }
    }
    
    
    
  • 相关阅读:
    搭建企业级Docker Registry -- Harbor
    搭建私服-docker registry
    CentOS 7.2修改网卡名称
    tomcat错误日志监控脚本
    Openresty+Lua+Redis灰度发布
    Jenkins权限控制-Role Strategy Plugin插件使用
    Rsyslog日志服务搭建
    awk4.0对数组value排序
    Spring-IOC 在非 web 环境下优雅关闭容器
    Spring-IOC bean 生命周期之 Lifecycle 钩子
  • 原文地址:https://www.cnblogs.com/alwayszzj/p/14982616.html
Copyright © 2011-2022 走看看