Get the App
SLTechnology News&Howtos  ›  Development  › 

Example Analysis of Java string reverse method

Shulou Source: shulou.com Published: 2022-06-01 04:28:06 10月25日 Update

Editor to share with you the Java string reverse method example analysis, I believe that most people do not know much about it, so share this article for your reference, I hope you will learn a lot after reading this article, let's go to know it!

1. Brief introduction

Record two ways to reverse the string:

The first method is violent, which reverses the string through the subscript of the string. Here, we use the substring () method of the String class, which is more commonly used, so we don't write it carefully.

The second method is to convert the String class to the StringBuffer class and reverse the string by calling the reverse () method of the StringBuffer class. This method is relatively simple.

The following is the implementation code for two methods:

Public class test_2_13 {public static void main (String [] args) {/ / TODO Auto-generated method stub String a = "123456"; String one = ""; String two = ""; / / method 1: for (int I = 0; I)

< a.length(); i++) { one += a.substring(a.length() - 1 - i, a.length() - i); } // 方法二: StringBuffer stringBuffer = new StringBuffer(a); two = stringBuffer.reverse().toString(); System.out.println("方法一输出效果:" + one); System.out.println("方法二输出效果:" + two); }}

Description:

Reverse the contents of a string str and output it.

Data range: 1\ le len (str)\ le 10000\ 1 ≤ len (str) ≤ 10000

Enter a description:

Enter a string with spaces

Output description:

Output a string in reverse order

Example 1

Enter:

I am a student

Copy output:

Tneduts a ma I

Example 2

Enter:

Nowcoder

Copy output:

Redocwon

two。 The code implements import java.util.*;public class Main {private String reverse (String str) {StringBuilder res = new StringBuilder (str); return res.reverse (). ToString ();} public Main () {Scanner in = new Scanner (System.in); while (in.hasNextLine ()) {String str = in.nextLine (); String res = reverse (str) System.out.println (res);}} public static void main (String [] args) {Main solution = new Main ();}} above is all the content of the article "sample Analysis of Java string reverse method". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Methods characters strings output examples reverse order input content articles analysis code effects subscript not much most commonly used data violence more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Docker MySQL Apple NVidia