有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (1) 个答案

  1. # 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;
    }