• 周六. 10 月 12th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

How to reverse the string of Java interview questions?

King Wang

1 月 3, 2022

We know , stay Java There are many ways to reverse a string , But what are the most commonly used ones ? Which method is the fastest ? Today I summarize four methods of string inversion , I hope it can help you .

String inversion method

(1) adopt StringBuilder Of reverse() Method , Claimed to be the fastest :

public class ReverseStringBuilder {
public static void main(String[] args) {
// TODO Auto-generated method stub
String d="acfbnm";// The string itself defines
ReverseStringBuilder(d);// call ReverseStringBuilder() Method
}
public static String ReverseStringBuilder(String s) {
// Specific implementation method
StringBuilder sb = new StringBuilder(s);
String AfterReverse=sb.reverse().toString();
System.out.println(AfterReverse);
return AfterReverse;
}
}

result :

 

(2) By recursion , It is said that they are taller :

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);
// In two parts
String AfterReverse = ReverseRecursive(right)+
ReverseRecursive(left);
// Call function recursively for two parts
return AfterReverse;
}
}

result :

(3) adopt charAt() Method :

/*
*
* This way is through charAt() Method to get each char character ,i=0 Get the first character a, then
* Assign to reverse, At this time, it only contains characters a; When i=1 when , Then get the second character b, And then add reverse
* The value of is assigned to reverse, here 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) adopt String Of toCharArray() Method , Character array :

// adopt String Of toCharArray() Method to get each string in the string and
// Convert to character array , Then use an empty string from the back to the front
// The concatenation for the new string .
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 contents are four kinds of string inversion methods arranged by the author , I hope that’s helpful !

Thank you. ! We grew up together !

发表回复