Only use : 1 variable string (for input), 1 variable char & 1 variable int
This implies, that the desired solution is:
- Take character from position
n
from String, store to character variable.
- Move variable
m
to n
(in string).
- restore cached char from character variable to position
m
.
- repeat until string is fully processed.
This is a typical question asked for "basic" programming languages. However Java does not allow for this, as it leaks the option to set a character based on position within a string.
While this is a no brainer in other languages, java has no option to set values based on an index for Strings.
public static String reverse(String str){
char c;
int i = 0;
for (i=0; i< str.length() / 2; i++){
c = str.charAt(i);
//this would be required to match your requirements.
str[i] = str.charAt(str.length() -1 -i);
str[str.length() -1 -i] = c;
}
return str;
}
but in java, you can only do:
public static String reverse(String str){
char c;
int i = 0;
for (i=0; i< str.length() / 2; i++){
c = str.charAt(i);
char[] temp = str.toCharArray();
temp[i] = str.charAt(str.length() -1-i);
temp[str.length() -1 -i] = c;
str = new String(temp);
}
return str;
}
which creates additional char
arrays and new String
objects... Even if you could lower this to one additional char array by declaring it out of the for
- loop, it does no longer match the requirement.
I think the guy designing the question was thinking in "C" or "php", where index-based access on strings is possible.
If a String would equal a char-array (which it does in some older languages, that might be the origin of this exercise) it would look like this:
public static char[] reverse(char[] str){
char c;
int i = 0;
for (i=0; i< str.length / 2; i++){
c = str[i];
str[i] = str[str.length -1-i];
str[str.length -1 -i] = c;
}
return str;
}