Write a program to print the reverse of the given string ?
***
Write a program to print the reverse of the given string.
Input
codecode
Output
edocedoc
Input Constraints
1<=Length of string<=100
Input string contains only lowercase characters ['a' to 'z'].
package
InterviewProgram;
import java.util.Scanner;
public class
ReverseStringWithRules
{
public static void main(String[] args)
{ Scanner scanner = new Scanner(System.in);
System.out.print("Input:
");
String input = scanner.nextLine();
if (input.length() < 1
|| input.length() > 100) {
System.out.println("Invalid
input length. Length should be between 1 and 100.");
return;
}
if (!input.matches("[a-z]+")) {
System.out.println("Invalid
input. Please enter a string with lowercase characters only.");
return;
}
String reversed = reverseString(input);
System.out.println("Output:
" + reversed);
}
public static String
reverseString(String input) {
StringBuilder reversed = new StringBuilder();
for (int i = input.length() - 1; i >= 0; i--) {
reversed.append(input.charAt(i));
}
return reversed.toString();
}
}
Output :
Input: dargablogs
Output: sgolbagrad
Explanation:
1. We start by importing the Scanner class, which allows us to take input from the user.2. In the main method, we prompt the user to input a string and store it in the input variable.
3. We check if the length of the input string is within the valid range (1 to 100) and also ensure that the input contains only lowercase characters using regular expression [a-z]+.
4.The reverseString method takes the input string as an argument and returns the reversed string. It uses a StringBuilder to build the reversed string by iterating through the characters of the input string in reverse order.
5.Finally, we print the reversed string as the output.
What is the output of
ReplyDeleteinput: "My name is Darga "
output: "Darga is name My"
https://dargablogs.blogspot.com/2023/08/word-reverse-program.html
Delete