zoukankan      html  css  js  c++  java
  • Java 练习(将字符串中指定部分进行反转)

    将一个字符串进行反转。将字符串中指定部分进行反转。比如"abcdefg"反转为"abfedcg"

    package com.klvchen.exer;
    
    import org.junit.Test;
    
    public class StringDemo {
        /*
        将一个字符串进行反转。将字符串中指定部分进行反转。比如"abcdefg"反转为"abfedcg"
    
        方式一: 转化为 char[]
         */
        public String reverse(String str, int startIndex, int endIndex){
    
            if (str != null && str.length() != 0){
                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);
    
                return reverseStr;
            }
            return null;
        }
        //方式三: 使用 StringBuffer/StringBuilder 替换 String
        public String reverse2(String str, int startIndex, int endIndex){
            if (str != null){
                StringBuffer builder = new StringBuffer(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 testReverse(){
            String str = "abcdefg";
    //        String reverse = reverse(str, 2, 5);
    //        String reverse = reverse1(str, 2, 5);
            String reverse = reverse2(str, 2, 5);
            System.out.println(reverse);
        }
    
    }
    

  • 相关阅读:
    服务部署 RPC vs RESTful
    模拟浏览器之从 Selenium 到splinter
    windows程序设计 vs2012 新建win32项目
    ubuntu python 安装numpy,scipy.pandas.....
    vmvare 将主机的文件复制到虚拟机系统中 安装WMware tools
    ubuntu 修改root密码
    python 定义类 简单使用
    python 定义函数 两个文件调用函数
    python 定义函数 调用函数
    python windows 安装gensim
  • 原文地址:https://www.cnblogs.com/klvchen/p/15216762.html
Copyright © 2011-2022 走看看