zoukankan      html  css  js  c++  java
  • Java实现字符串反转

    对于使用Java字符串反转有以下几种实现:

    • 利用StringBuilder类中的reverse函数;
    • 使用递归,将String的首字符放到除首字符外的子串后,然后再递归调用子串;
    • 使用字符数组做reverse;
    public class Reverse {
    	public static String reverse1(String str) {
    		if (str == null || str.length() <= 1)
    			return str;
    		return new StringBuilder(str).reverse().toString();
    	}
    	
    	public static String reverse2(String str) {
    		if (str == null || str.length() <= 1)
    			return str;
    		return reverse2(str.substring(1)) + str.charAt(0);
    	}
    	
    	public static String reverse3(String str) {
    		if (str == null || str.length() <= 1)
    			return str;
    		char[] ca = new char[str.length()];
    		for (int i = 0; i < str.length(); i++) {
    			ca[i] = str.charAt(str.length() - i - 1);
    		}
    		return new String(ca);
    	}
    	
    	public static void main(String[] args) {
    		String s = "hello world";
    		
    		System.out.println(reverse1(s));
    		System.out.println(reverse2(s));
    		System.out.println(reverse3(s));
    	}
    }
    ------------------------------- 问道,修仙 -------------------------------
  • 相关阅读:
    leetCode-Two Sum
    leetCode-Pascal's Triangle II
    leetCode-Maximum Average Subarray I
    css 实现垂直水平居中
    poping 心法
    我的机密
    MSMQ消息队列的使用
    生成最大单号 scope_identity
    sqlserver ADO.net 查询数据库加锁,事务提交
    漂亮的JS插件
  • 原文地址:https://www.cnblogs.com/elvalad/p/4072380.html
Copyright © 2011-2022 走看看