Reputation: 2890
I have the following code to reverse a string, and I am considering to make test cases for it. I would like to know how to handle cases like when user input "\n", "\t" ?
private static String reverse2(String str) {
if (str == null || str.length() == 0)
return str;
int start = 0;
int end = str.length() - 1;
char[] chars = str.toCharArray();
while (start < end) {
char tmp = chars[start];
chars[start] = chars[end];
chars[end] = tmp;
start++;
end--;
}
return String.valueOf(chars);
}
Upvotes: 2
Views: 1598
Reputation: 179
In strings like "\nxyz", str.toCharArray() treats "\n" as a single character. There is no issue in your code. Only thing place of new line char will change and it will print in different line format this time.
Upvotes: 4
Reputation:
Your question is ambiguous and the answer not so simple.
If what you call user input is a Java literal string like "newline -\n-"
, the sequence \n
is turned into a single newline character. When you print the string, you don't see the \n
anymore. Instead, further output goes to the next line, giving
newline -
-
(11 characters). Reversal gives
-
- enilwen
On the opposite, if user input is from the keyboard, the escapes will not be recognized and a print will output the string unchanged.
newline -\n-
(12 characters). Reversal gives
-n\- enilwen
If you want the escapes to be recognized and translated, you need to do that yourself by checking every input character.
In the weirdest of the cases, you can restore the escapes after reversal (so that they become visible again), giving the transforms
newline -\n-
(12 characters) then internally,
newline -
-
(11 characters) then internally reversed,
-
- enilwen
(11 characters) then externally
-\n- enilwen
(12 characters). Notice the difference with above n\
vs \n
.
Upvotes: 2
Reputation: 4768
Why not reverse it using a StringBuilder:
string input = "xyz\t\nabc123";
string reversed = new StringBuilder(input).reverse().toString();
Upvotes: 3
Reputation: 2081
StringBuilder str = new StringBuilder("Java");
// reverse characters of the StringBuilder and prints it
System.out.println("reverse = " + str.reverse());
Upvotes: 4