Home > Article > Computer Tutorials > JAVA program: implement string reversal
1. Write a JAVA program to display a string in reverse?
To write a Java program to display a string in reverse, you can use the following code example:
public class ReverseString { public static void main(String[] args) { String original = "Hello, World!"; String reversed = reverseString(original); System.out.println("Original String: " + original); System.out.println("Reversed String: " + reversed); } private static String reverseString(String str) { StringBuilder reversed = new StringBuilder(); for (int i = str.length() - 1; i >= 0; i--) { reversed.append(str.charAt(i)); } return reversed.toString(); } }
This program defines a reverseString
method, which Accepts a string and returns its reverse version. In the main
method, we demonstrate how to use this method.
2. String replacement in java How to perform string replacement in ja?
In Java, you can use the replace
method to perform string replacement. Here is a simple example:
public class StringReplaceExample { public static void main(String[] args) { String original = "Java is fun!"; String replaced = original.replace("fun", "awesome"); System.out.println("Original String: " + original); System.out.println("String after replacement: " + replaced); } }
In the above example, we use the replace
method to replace "fun" with "awesome" in the original string. The replaced string is stored in the replaced
variable.
Please note that the replace
method returns a new string and the original string remains unchanged.
Summary
’s
reverse method or construct the reverse string by iteration.
method to perform string replacement. A new string will be created, leaving the original string unchanged.
The above is the detailed content of JAVA program: implement string reversal. For more information, please follow other related articles on the PHP Chinese website!