簡體   English   中英

你如何在java中逐個字符地反轉字符串?

[英]How do you reverse a string character by character in java?

假設我有一個帶有短語“美國銀行”的字符串。 我想反轉它,所以輸出結果為“aciremA fo knaB”

這是我一直在嘗試使用的代碼,但輸出只是最后一個單詞的最后一個字母,即“a”

int position = phraseLength;
for(int index = position-1; index >= 0; index--);
System.out.println(p1.charAt(position-1));

我不確定這里出了什么問題,所以會有任何幫助。

    StringBuffer sb=new StringBuffer("Bank of America");
    System.out.println(sb.reverse());

如果你想按照自己的方式去做。 利用

    int position = phraseLength;
    for(int index = position-1; index >= 0; index--)
        System.out.println(p1.charAt(index));

您在此處的 for 循環后添加了一個額外的分號

for(int index = position-1; index >= 0; index--);
                                                ^

此外,您總是在訪問postion-i 您應該訪問index

System.out.println(p1.charAt(position-1));
                             ^^^^^^^^^^^
                                here

你可以用這個

int position = phraseLength;
for(int index = position-1; index >= 0; index--)
    System.out.print(p1.charAt(index));

或這個

String output = "";
int position = phraseLength;
for(int index = position-1; index >= 0; index--)
    output+=p1.charAt(index);
System.out.println(output);

我猜你錯誤地在 for 循環之后添加了semicolon 實際上這不會給出任何compile time error 但是循環的內容只會被執行一次。 所以刪除分號並完成它!

public String reverse(String str) {   
 char [] buffer = str.toCharArray();

 for (int i = 0, j = buffer.length - 1; i < j; i++, j--) {
  char temp = buffer[i];
  buffer[i] = buffer[j];
  buffer[j] = temp;
 }

 return new String(buffer);
}
StringBuffer stringBuffer=new StringBuffer("Bank of America");
System.out.println(stringBuffer.reverse());    

聲明一個字符串。 取出該字符串的長度。 循環遍歷字符串的字符。 在新字符串中以相反的順序添加字符。 字符串 str = "你好";

字符串反向 = "";

int 長度 = str.length();

for (int i = 0; i < 長度; i++) {

 reverse = str.charAt(i) + reverse;

}

System.out.println(reverse);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM