reversing a String in java [closed]
Code to revers a string in java: NOTE: One or two additional variables are fine. An extra copy of the array is not.
Now i have implemented a algo as follows:
public static void removeDuplicates(char[] str) {
if (str == null) return;
int len = str.length;
if (len < 2) return;
int tail = 1;
for (int i = 1; i < len; ++i) {
int j;
for (j = 0; j < tail; ++j) {
if (str[i] == str[j]) break;
}
if (j == tail) {
str[tail] = str[i];
++tail;
}
}
str[tail] = something //something to mark end of char array eg '\0' as we have in C
}
I would do it such (pseudocode):
// s is array of char that holds the string
i=0
j=s.length - 1
while (i < j)
swap characters at positions i and j
i++
j--
Try Apache Commons StringUtils class:
http://commons.apache.org/lang/api-2.3/org/apache/commons/lang/StringUtils.html
It has a great reverse function:
static String reverse(String str);
you cannot reverse a String in java without extra space, because String is immutable in java.
seems like a trick question...
if you want to revers char[] it should be something like:
char[] str = "abcdefg".toCharArray();
int len = str.length;
int n = len / 2;
for (int i = 0;i<n;i++) {
char temp = str[i];
str[i] = str[len-1-i];
str[len-1-i] = temp;
}
System.out.println(str);
As said, reversing a String object is not possible, as string objects in Java are immutable.
You could circumvent this by using reflection to access the underlying array (see below), but this is not advisable.
If we take a question as working on a char[]
(or any other array) instead, it gets easy:
/**
* reverses an array by swapping its elements.
*/
public static void reverse(char[] array) {
reverse(array, 0, array.length);
}
/**
* reverses a section of an array by swapping its elements.
* @param start the start of the section, inclusive
* @param end the end of the section, exclusive
*/
public static void reverse(char[] array, int start, int end) {
for(int i = start, j = end-1; i < j; i++, j--) {
swap(array, i, j);
}
}
/**
* swaps two array elements.
*/
private static void swap(char[] array, int i, int j) {
char help = array[i];
array[i] = array[j];
array[j] = help;
}
Having this, we can now also cheat to reverse an existing string:
public static void reverse(String s) {
Class<String> sClass = String.class;
char[] array = (char[])sClass.getDeclaredField("value").get(s);
int start = sClass.getDeclaredField("offset").getInt(s);
int len = sClass.getDeclaredField("count").getInt(s);
reverse(array, start, start+len);
}
As said, this is not advisable since the whole VM and standard library is based on the fact that Strings are immutable. Also, the field names here are taken from the 1.6.0_13 Sun implementation, other VMs may have other names for these fields, or store strings in another way altogether.
Maybe something like this?
string input = "ABCD";
string result = "";
for (int i = input.length-1; i >= 0; i--)
{
result = result + input[i];
}
精彩评论