java 保留字符串,如何在Java中保留字符串而不使用反转功能

有以下几种在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

}

}

}

输出:

how-to-reserve-a-string-in-java-without-using-reverse-function-output1.png

使用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

}

}

}

输出:

how-to-reserve-a-string-in-java-without-using-reverse-function-output2.png

使用静态方法

使用静态方法在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;

}

}

输出:

how-to-reserve-a-string-in-java-without-using-reverse-function-output3.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值