【问题标题】:Reversing a string without using any built in methods [duplicate]在不使用任何内置方法的情况下反转字符串[重复]
【发布时间】:2012-05-10 01:39:25
【问题描述】:

可能重复:
Printing reverse of any String without using any predefined function?

请告知如何在不使用内置方法的情况下反转字符串。我只想使用字符串类,请建议说有一个字符串“john is a boy”并打印“yob a si nhoj”。

【问题讨论】:

  • 您需要使用可变的字符序列。
  • 这样的事情怎么样:dotnetperls.com/reverse-string。使用数组?
  • 投票结束 - 这个问题可以被互联网上的一千个页面回答......

标签: java


【解决方案1】:

此方法将向后返回字符串。您所要做的就是向后遍历字符串并将其添加到另一个字符串中。

您使用 for 循环来执行此操作,但首先检查字符串的长度是否大于 0。

Java 字符串有一个方法“charAt(index)”,它返回字符串位置上的单个字符,其中位置 0 是第一个字符。因此,如果您想反转“Boy”,您可以从字母 2 开始,然后是 1,然后是 0,然后将它们全部添加到一个新字符串中,从而得到“yoB”。

public static String reverseString(String inString) {
    String resultString = "";//This is the resulting string, it is empty but we will add things in the next for loop
    if(inString.length()>0) {//Check the string for a lenght greater than 0
        //here we set a number to the strings lenght-1 because we start counting at 0
        //and go down to 0 and add the character at that position in the original string to the resulting one
        for(int stringCharIndex=inString.length()-1;stringCharIndex>=0;stringCharIndex--) {
            resultString+=inString.charAt(stringCharIndex);
        }
    }
    //finaly return the resulting string.
    return resultString;
}

【讨论】:

  • @mprivat:同意,尽管学生可以通过任意数量的网络搜索找到许多许多明确的解决方案。
  • 哎呀没有看到作业标签。我只是想帮忙。没有理由在没有警告的情况下投反对票。对不起
  • @mprivat 你shouldn't downvote people也回答家庭作业问题
  • 谢谢。至少我试着解释一下它是如何工作的。
【解决方案2】:

您可以遍历字符串中的所有字符,并使用 insert(0, char) 方法将它们添加到 StringBuffer 中。然后在迭代结束时,您的 StringBuffer 将是反转的字符串。

【讨论】:

  • "我只想使用字符串类"
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 2021-05-13
  • 1970-01-01
相关资源
最近更新 更多