2012-05-09 29 views
0

可能重複:
Printing reverse of any String without using any predefined function?倒車字符串,而無需使用任何內置的方法

請指教如何扭轉一個字符串,而不使用內置的方法。我只想使用字符串類,請告訴我們假設有一個字符串「john是個男孩」並且打印出「yob a si nhoj」。

+0

*任何*內置方法? –

+0

您需要使用可變字符序列。 –

+0

這樣的事情如何:http://www.dotnetperls.com/reverse-string。使用數組? – w0051977

回答

0

該方法將向後返回字符串。你所要做的就是向後遍歷字符串並將其添加到另一個字符串中。

你做到這一點使用一個for循環,但如果字符串大於a lenght第一檢查0

Java字符串具有其上的位置返回單個字符的方法「的charAt(指數)」字符串,其中位置0是第一個字符。所以如果你想反轉「男孩」,你可以從字母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; 
} 
+0

@mprivat:同意,雖然學生可以通過做任何數量的搜索網絡找到許多,*許多*明確的解決方案。 – maerics

+1

oops沒有看到作業標籤。我只是想幫助。沒有理由不經警告就退縮。對不起 –

+3

@mprivat你[不應該downvote人](http://meta.stackexchange.com/a/10812/145982)誰回答作業問題 –

0

您可以遍歷字符串中的所有字符,並使用insert(0,char)方法將它們前置到StringBuffer中。然後在迭代結束時,你的StringBuffer將是反轉的字符串。

+0

「我只想使用字符串類」 –

相關問題