Uncategorized

Different Ways to Reverse the String in Java

  1. Using the toCharArray and swap the location of the char
    public static String firstWayToReverse(String str) {
    if (str == null) {
    return null;
    }
    char[] charStr = str.toCharArray();
    for (int i = 0; i < charStr.length / 2; i++) {
    char temp = charStr[i];
    charStr[i] = charStr[charStr.length - (i + 1)];
    charStr[charStr.length - (i + 1)] = temp;
    }
    for (char eachChar : charStr) {
    System.out.println(eachChar);
    }
    return String.valueOf(charStr);
    }
  2. Using StringBuffer
    public static String SecondWayToReverse(String str) {
    if (str == null) {
    return null;
    }
    return new StringBuffer(str).reverse().toString();
    }
  3. Using StringBuilder
    public static String FourthWayToReverse(String str) {
    if (str == null) {
    return null;
    }
    return new StringBuilder(str).reverse().toString();
    }
  4. Using BruteForce
    public static String FifthWayToReverse(String str) {
    if(str == null) {
    return null;
    }
    String revStr = "";
    for (int i = (str.length() - 1); i >= 0; i--) {
    revStr += String.valueOf(str.charAt(i));
    }
    return revStr;
    }

Please put your comments and let’s know if there are any other ways to reverse the String.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s