新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
java實(shí)現(xiàn)字符串反轉(zhuǎn)案例-創(chuàng)新互聯(lián)
本文實(shí)例為大家分享了java實(shí)現(xiàn)字符串反轉(zhuǎn)的具體代碼,供大家參考,具體內(nèi)容如下
1.需求:
定義一個方法,實(shí)現(xiàn)字符串反轉(zhuǎn)。鍵盤錄入一個字符串,調(diào)用該方法后,在控制臺輸出結(jié)果
例如,鍵盤錄入abc,輸出結(jié)果cba
2.思路:
1.鍵盤錄入一個字符串,用Scanner實(shí)現(xiàn)
2.定義一個方法,實(shí)現(xiàn)字符反轉(zhuǎn)。返回值類型String,參數(shù)String s
3.在方法中把字符串倒著遍歷,然后把每一個得到的字符拼接成一個字符串并返回
4.調(diào)用方法, 用一個變量接收結(jié)果
5.輸出結(jié)果
3.代碼實(shí)現(xiàn)
import java.util.Scanner; public class StringReverse { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入一個字符串:"); String line = sc.nextLine(); String str = String_reverse(line); System.out.println("s:" + str); } public static String String_reverse(String s) { String s1 = ""; for (int i = s.length() - 1; i >= 0; i--){ s1 += s.charAt(i); } return s1; } }
新聞標(biāo)題:java實(shí)現(xiàn)字符串反轉(zhuǎn)案例-創(chuàng)新互聯(lián)
分享地址:http://www.dlmjj.cn/article/ccpdej.html