Use only: 1 variable string (for input), 1 char variable and 1 int variable
It follows that the desired solution:
- Take a character from position
n
of a String, store it in a character variable. - Move the variable
m
to n
(per line). - restore cached char with character variable to position
m
. - repeat until the line is fully processed.
This is a typical question asked for "basic" programming languages. However, Java does not allow this, since it eliminates the possibility of setting a character based on a position within a string.
Although this is not a problem in other languages, java does not have the ability to set index-based values ββ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);
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 can omit this into one additional char array by declaring it from a for
loop, it no longer meets the requirement.
I think the guy asking the question thought in "C" or "php" where index-based access to strings is possible.
If String is equal to char -array (which it does in some older languages, which may be the source of this exercise), it will 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; }
source share