如何逐字反转Java Word中的字符串

在本节中, 我们逐字反转Java中的字符串。
示例1:使用递归逐个单词地反转字符串

import java.util.Scanner; public class ReverseStringExample1 {public static void main(String[] args) {String str; System.out.println("Enter a string: "); Scanner scanner = new Scanner(System.in); str = scanner.nextLine(); scanner.close(); //closes the input streamString reversed = reverseString(str); System.out.println("The reversed string is: " + reversed); }public static String reverseString(String s){if (s.isEmpty())//checks the string if emptyreturn s; return reverseString(s.substring(1)) + s.charAt(0); //recursively called function}}

输出:
如何逐字反转Java Word中的字符串

文章图片
示例2:使用for循环逐字逆转字符串
import java.util.*; public class ReverseStringDemo{public static void main(String[] arg){ReverseStringDemo rs=new ReverseStringDemo(); Scanner sc=new Scanner(System.in); System.out.print("Enter a string: "); Stringstr=sc.nextLine(); System.out.println("Reverse of a Stringis : "+rs.reversestr(str)); //called method}//reverse string methodstatic String reversestr(String s){String r=""; for(int i=s.length(); i> 0; --i)//execute until condition i> 0 becomes false{r=r+(s.charAt(i-1)); }return r; }}

【如何逐字反转Java Word中的字符串】输出:
如何逐字反转Java Word中的字符串

文章图片

    推荐阅读