Home> Java> javaTutorial> body text

Example analysis of Java string reverse order method

WBOY
Release: 2023-04-20 11:28:13
forward
1283 people have browsed it

1. Brief description

Record two methods to achieve string reverse order:

  • The first method is more violent, through The subscript of the string reverses the string. The substring() method of the String class is used here. This method is more commonly used, so I won’t write it down in detail.

  • The second method is Convert theStringclass into theStringBufferclass, and reverse the string by calling the reverse() method of the StringBuffer class. This method is relatively simple

The following is the implementation code of the 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 = ""; // 方法一: 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); } }
Copy after login

Example analysis of Java string reverse order method

##Description:

Convert a The contents of the string str are reversed and output.

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

Input description:

Input a string, there can be spaces

Output description:

Output the string in reverse order

Example 1

Input:

I am a student
Copy after login

Copy Output:

tneduts a ma I

Example 2

Input:

nowcoder
Copy after login

Copy output:

redocwon

2. Code implementation

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

The above is the detailed content of Example analysis of Java string reverse order method. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!