简体   繁体   中英

Reverse String without using StringBuffer.reverse()

What is the problem in following example? what happens if millions of Char in the String to be Reversed?

public static String reverseUsingStringBuffer(String source) {
    if(source == null || source.isEmpty()){
        return source;
    }       
    StringBuffer reverse = new StringBuffer();

    for(int i = source.length() -1; i>=0; i--){
        reverse.append(source.charAt(i));
    }

    return reverse.toString();
}

Is following better approach? (beside using api method). What is the good approach for huge String?

public static String reverse(String source) {
    if(source == null || source.isEmpty()){
        return source;
    }       
    String reverse = "";
    for(int i = source.length() -1; i>=0; i--){
        reverse = reverse + source.charAt(i);
    }

    return reverse;
}

As already said, the String approach is pretty bad. Using StringBuffer is much better, but there's no reason for this rather obsolete class, when StringBuilder can do the same faster.

Even simpler and faster in this case is to use an array:

char[] result = new char[source.length];
for(int i = 0; i < source.length(); ++i) result[source.length() - 1 - i] = source.charAt(i);
return new String(result);

This allocates no garbage at all.... except for the char[] , but this is unavoidable as String is immutable and the sharing constructor is package-private (for a good reason).

Note that usually there's absolutely no need to optimize that hard.

No, the first approach is better because it will internally manage your buffers for you. Don't try to outsmart the compiler. Why didn't you append the entire source in one line, which will properly allocate your buffer.

The first one. In the second you use "string = string + string" and this creates one object every time you use "+". I'd sugest StringBuffer.

第一种方法更好,StringBuffer是可变的,并且使用string = string + string会降低性能。

You can make it in place as well.

public static String reverse(String s) {
   char[] chars = s.toCharArray();
   for(int i = 0, j = chars.length - 1; i < chars.length / 2; i++, j--) {
     char c = chars[i];
     chars[i] = chars[j];
     chars[j] = c;
   }
   return new String(chars);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM