Java字符串逆序方法詳情
1.簡述
記錄下實(shí)現(xiàn)字符串逆序的兩種方法:
- 第一種方法比較暴力,通過字符串的下標(biāo)將字符串逆轉(zhuǎn)過來,這里要用到String類的substring()方法,這個方法比較常用,就不仔細(xì)寫了
- 第二中方法是將
String類轉(zhuǎn)換成StringBuffer類,通過調(diào)用StringBuffer類的reverse()方法將字符串逆轉(zhuǎn),這個方法比較簡單
下面是兩種方法的實(shí)現(xiàn)代碼:
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);
? ? }
}
描述:
將一個字符串str的內(nèi)容顛倒過來,并輸出。
數(shù)據(jù)范圍:1 \le len(str) \le 10000\1≤len(str)≤10000
輸入描述:
輸入一個字符串,可以有空格
輸出描述:
輸出逆序的字符串
示例1
輸入:
I am a student
復(fù)制輸出:
tneduts a ma I
示例2
輸入:
nowcoder
復(fù)制輸出:
redocwon
2.代碼實(shí)現(xiàn)
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();
? ? }?
}到此這篇關(guān)于Java字符逆序詳情的文章就介紹到這了,更多相關(guān)Java字符逆序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java Excel透視表相關(guān)操作實(shí)現(xiàn)代碼
這篇文章主要介紹了Java Excel透視表相關(guān)操作實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-08-08
Mybatisplus自動填充實(shí)現(xiàn)方式及代碼示例
這篇文章主要介紹了Mybatisplus自動填充實(shí)現(xiàn)方式及代碼示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11
SpringBoot整合Sharding-JDBC實(shí)現(xiàn)MySQL8讀寫分離
本文是一個基于SpringBoot整合Sharding-JDBC實(shí)現(xiàn)讀寫分離的極簡教程,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的可以了解一下2021-07-07
Mybatis的TypeHandler加解密數(shù)據(jù)實(shí)現(xiàn)
在我們數(shù)據(jù)庫中有些時候會保存一些用戶的敏感信息,所以就需要對這些數(shù)據(jù)進(jìn)行加密,那么本文就介紹了Mybatis的TypeHandler加解密數(shù)據(jù)實(shí)現(xiàn),感興趣的可以了解一下2021-06-06
swing組件JScrollPane滾動條實(shí)例代碼
這篇文章主要介紹了swing組件JScrollPane滾動條實(shí)例代碼,分享了兩個相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下2018-02-02

