JAVA program: implement string reversal

PHPz
Release: 2024-01-17 15:36:04
forward
748 people have browsed it

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();
    }
}
Copy after login

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);
    }
}
Copy after login

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

    ##1.
  1. Reverse string display: Use StringBuilder’s reverse method or construct the reverse string by iteration.
  2. 2.
  3. String replacement: Use the replace method to perform string replacement. A new string will be created, leaving the original string unchanged.

JAVA program: implement string reversal

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!

source:docexcel.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template