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));
    	}
    }
    ------------------------------- 问道,修仙 -------------------------------
  • 相关阅读:
    hdu 2222 Keywords Search
    Meet and Greet
    hdu 4673
    hdu 4768
    hdu 4747 Mex
    uva 1513 Movie collection
    uva 12299 RMQ with Shifts
    uva 11732 strcmp() Anyone?
    uva 1401
    hdu 1251 统计难题
  • 原文地址:https://www.cnblogs.com/elvalad/p/4072380.html
Copyright © 2011-2022 走看看