Thursday, 16 June 2016

Write a method to reverse a String in java.

In Java, a String is immutable, so once it has been constructed it is not possible to change the contents. So when you are asked to reverse a String, you are actually being asked to produce a new String object, with the contents reversed,


public static String reverse(final String s)

Approach to reversing a String is to iterate over the contents in reverse

public static String reverse(final String s) {
final StringBuilder sb = new StringBuilder(s.length());
for (int i = s.length() - 1; i >= 0; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}

Or we can do by using Built-in Re verse Methods

Note-This approach, is fine when we do it with small size of data,  It hold the original String and the StringBuilder in memory and occupy large memory. This could be problematic if you were reversing some data of several gigabytes in size.



public static String stringReverse(final String s) {
final StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() / 2; i++) {
final char tmp = sb.charAt(i);
final int otherEnd = sb.length() - i - 1;
sb.setCharAt(i, sb.charAt(otherEnd));
sb.setCharAt(otherEnd, tmp);
}
return sb.toString();
}

No comments:

Post a Comment

Find Duplicate Characters In String using Java

package com.zia.test; import java.util.HashMap; import java.util.Map; import java.util.Set; public class findDuplicateCharacter { /**...