Write a piece of java code that reverses a string please
- User
Write a piece of java code that reverses a string please
Assistant
Here is Java code to reverse a string:
public class ReverseString { public static String reverse(String input) { StringBuilder reversed = new StringBuilder(); for(int i = input.length()-1; i >= 0; i--) { reversed.append(input.charAt(i)); } return reversed.toString(); } public static void main(String[] args) { String input = "Hello World"; String reversed = reverse(input); System.out.println(reversed); // dlroW olleH } }To explain, it:
- Creates an empty StringBuilder that will hold the reversed string
- Iterates through the input string backwards using a for loop
- Appends each character to the StringBuilder
- Converts the StringBuilder to a String and returns it
So it reverses the string by iterating through it in reverse order and appending each character, ultimately returning the final reversed string.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.