Wednesday, December 30, 2009

string manipulation in java part 1: reverse a string

In these series, I'll try to provide code fragments for daily problems in string manipulation. First, we will see how to reverse a string. Note that there are -naturally- more than one way to do this.


public class StringUtils {
public static String reverseString(String string){
/*
Check if the string is not null and empty
*/

if(string != null && !string.isEmpty()){

/*
Create a StringBuilder from the string in hand
*/

StringBuilder str = new StringBuilder(string);

/*
Reverse the StringBuilder content and return it as a String
*/

return str.reverse().toString();
}
return null;
}

public static void main(String[] args){
System.out.println(StringUtils.reverseString("I am your father"));
}
}



Output is "rehtaf ruoy ma I".
It is possible to use StringBuffer instead of StringBuilder. As I don't need thread safety I'll pick StringBuilder which's faster. Quite easy to reverse a string, right?

No comments:

Post a Comment