Switch to full style
General Java code examples
Post a reply

recursive string reversal- reverse string

Tue Dec 02, 2008 1:30 pm

If you want to to reverse a string . I will show you two ways the first one is using the reverse method in jdk ,it is powerful function and easy .

java code
public class MyClass {
public String reverse(String newstring) {
if ((null == newstring) || (newstring.length() <= 1)) {
return newstring;
}
return new StringBuffer(newstring).reverse().toString();
}
}


Notice that is no need to reverse a string with length =1 .

another solution is using recursion ,yes recursion , the idea is basic ,i know many programmers don't like recursion , but it is easy if you just think in it for a minute . ,take a look to code .

java code
public String reverse(String newstring) {
if ((null == newstring) || (newstring.length() <= 1)) {
return newstring;
}
return reverse(newstring.substring(1)) + newstring.charAt(0);
}


other solutions you may need it or think about ,

1- Do a swap in StringBuffer
java code
public String reverseusingswap(String newstring) {
if ((null == newstring) || (newstring.length() <= 1 )) {
return newstring;
}
StringBuffer stringresult = new StringBuffer(newstring);
for (int i = 0; i < (newstring.length() / 2); i++) {
int swapIndex = newstring.length() - 1 - i;
char swap = stringresultcharAt(swapIndex);
stringresult.setCharAt(swapIndex, stringresult.charAt(i));
stringresult.setCharAt(i, swap);
}
return stringresult.toString();
}



2. Swap an array

java code
public String reverse(String newstring) {
if ((null == newstring) || (newstring.length() <= 1)) {
return newstring;
}
char[] chars = newstring.toCharArray();
int right = chars.length - 1;
for (int left = 0; left < right; left++) {
char swap = chars[left];
chars[left] = chars[right];
chars[right--] = swap;
}
return new String(chars);
}


Another Example
java code
ReverseString {
public static String reverseIt(String source) {
int i, len = source.length();
StringBuffer dest = new StringBuffer(len);

for (i = (len - 1); i >= 0; i--)
dest.append(source.charAt(i));
return dest.toString();
}
}




Post a reply
  Related Posts  to : recursive string reversal- reverse string
 check if string ends with specific sub-string in php     -  
 Splitting a String Based on a Found String     -  
 check if string start with a specific sub-string in PHP     -  
 String token for string split     -  
 Pad a string to a certain length with another string     -  
 String Sort     -  
 get string length in asp     -  
 Echoing a String     -  
 replacing each tab by the string “Tab”,     -  
 String Flatten (C++)     -  

Topic Tags

Java Strings