Java interview questions reversal string of several common ways?

We know that there are many ways to reverse a string in Java will be, but the most common, which has several of it? Which method is the fastest speed of it? Today I summarize these four methods to reverse a string, hoping to be helpful to everyone.

String reversal method

(1) through a StringBuilder reverse () method, known as the fastest:

public class ReverseStringBuilder {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String d="acfbnm";//字符串自己定义
		ReverseStringBuilder(d);//调用ReverseStringBuilder()方法
	}
	public static String ReverseStringBuilder(String s) {
        //具体实现方法
		StringBuilder sb = new StringBuilder(s);
		String AfterReverse=sb.reverse().toString();
		System.out.println(AfterReverse);
		return AfterReverse;
	}
}

result:

 

(2) by recursive said relatively tall on:

public class ReverseRecursive {

	public static void main(String[] args) {
		String f="123456";
		System.out.println(ReverseRecursive(f));

	}
	public static String ReverseRecursive(String s) {
		int length =s.length();
		if(length<=1)
			return s;
		String left=s.substring(0, length/2);
		String right=s.substring(length/2,length);
		//分为两部分
		String AfterReverse = ReverseRecursive(right)+
				ReverseRecursive(left);
		//对两部分分别递归调用函数
		return AfterReverse;
	}
}

result:

(3) by the charAt () Method:

/*
 * 
 * 这种方法是通过charAt()方法获得每一个char字符,i=0时获得第一个字符a,然后
 * 赋给reverse,此时这里面仅包含字符a;当i=1时,然后获得第二个字符b,然后加上reverse
 * 的值在赋值给reverse,此时reverse=“ba”*/

public class CharAtreverse {
     public static void main(String[] args) {
	     String f="abcdefg";
	     CharAtreverse(f);	
}
public static String CharAtreverse(String s) {
	int length = s.length();
	String reverse = "";
	for(int i=0;i<length;i++)
		reverse = s.charAt(i)+reverse;
	System.out.println(reverse);
	return reverse;
    }
}

result:

(4) by a toCharArray String () method, i.e. an array of characters:

//通过String的toCharArray()方法可以获得字符串中的每一个字符串并且
//转化为字符数组,然后使用一个空的字符串从后向前一个个
//的拼接为新的字符串。

public class ReverseCharArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String f="abcdrf";
		ReverseCharArray(f);
	}
	public static String ReverseCharArray(String s) {
		char[] array=s.toCharArray();
		String reverse = "";
		for(int i=array.length-1;i>=0;i--) {
			reverse+=array[i];
		}
		System.out.println(reverse);
		return reverse;
	}
}

result:

 

The above is the author finish four string reverse way, we want to help!

thank you all! We grow together!

Guess you like

Origin blog.csdn.net/qq_41026809/article/details/90645616