如何使用for循环制作反向字符串? [英] How to make a reverse string using a for loop?

查看:72
本文介绍了如何使用for循环制作反向字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要让我的代码以相反的顺序输出字符串.例如,输出应将code"返回为edoc".这就是我迄今为止所做的.

I need to have my code output the String in reverse order. For example, the output should have "code" return as "edoc". This is what I have done so far.

public String reverseString(String str) {
 String res = "";

for (int i = 0; i <= str.length()-1; i++) {
   res = res + str.charAt(i);
 }
  return res;
}

推荐答案

你的串联是倒退的.试试:

You have your concatenation backwards. Try:

public String reverseString(String str) {
    String res = "";
    for (int i = 0; i < str.length(); i++) {
       res = str.charAt(i) + res;            // Add each char to the *front*
    }
    return res;
}

还要注意更简单、规范的循环终止条件.

Note also the simpler, canonical, loop termination condition.

这篇关于如何使用for循环制作反向字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆