有以下幾種在Java中反轉字符串的方法:
使用for循環
使用While循環
使用靜態方法
使用For循環
使用for循環在Java中反轉字符串的示例
在下面的示例中, 我們使用了for循環來反轉字符串。 for循環執行直到條件i> 0變為false為止。
import java.util.Scanner;
class ReverseStringExample1
{
public static void main(String args[])
{
String s;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String: ");
s=sc.nextLine();//reading string from user
System.out.print("After reverse string is: ");
for(int i=s.length();i>0;--i)//i is the length of the string
{
System.out.print(s.charAt(i-1));//printing the character at index i-1
}
}
}
輸出:
使用while循環
使用while循環在Java中反轉字符串的示例
在以下示例中, i是字符串的長度。 while循環執行直到條件i> 0變為false為止, 即, 如果字符串的長度為0, 則游標終止執行。它打印在索引(i-1)處的字符串的字符, 直到i> 0。
import java.util.Scanner;
class ReverseStringExample2
{
public static void main(String args[])
{
String s;
Scanner sc=new Scanner(System.in); //reading string from user
System.out.print("Enter a String: ");
s=sc.nextLine();
System.out.print("After reverse string is: ");
int i=s.length();//determining the length of the string
while(i>0)
{
System.out.print(s.charAt(i-1)); //printing the character at index i-1
i--; //decreasing the length of the string
}
}
}
輸出:
使用靜態方法
使用靜態方法在Java中反轉字符串的示例
在下面的示例中, 我們創建了該類的對象, 并通過傳遞給定的字符串將該對象稱為rev.reverse(s)調用了靜態方法。
import java.util.Scanner;
public class ReverseStringExample3
{
public static void main(String[] arg)
{
ReverseStringExample3 rev=new ReverseStringExample3();
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string : ");
String s=sc.nextLine();
System.out.println("Reverse String is : "+rev.reverse(s));//calling method
}
//calling method
static String reverse(String str)
{
String rev="";
for(int i=str.length();i>0;--i)
{
rev=rev+(str.charAt(i-1));
}
return rev;
}
}
輸出: