簡體   English   中英

如何在不使用數組、split() 或 StringBuilder 的情況下逐字反轉字符串

[英]How can I reverse a string word by word without using arrays, split() or StringBuilder

我試圖在不使用數組、 split()StringBuilder情況下逐字反轉字符串。 到目前為止,這是我的代碼。 它有效,但我的輸出不是我想要的。 請參閱我的圖像以獲取輸出。 我希望我的程序在新行上輸出每個單詞。 還要注意窗簾中的字母“n”是如何丟失的,並且最后兩個單詞之間沒有空格。 我怎樣才能解決這個問題?

public static void main(String[] args) {

    String sentence = new String("pay no attention to that man behind the curtain");
    String reversed = "";

    int endIndex = sentence.length()-1;
    for(int i = endIndex; i >= 0; i--) {
        if(sentence.charAt(i) == ' ') {
            reversed += sentence.substring(i, endIndex);
            endIndex = i;
        }
    }
    reversed += sentence.substring(0, endIndex);
    System.out.println(reversed);
}

在此處輸入圖片說明

試試這個代碼:

import java.util.Scanner;
 
public class ReverseString
{
 public static void main(String[] args)
 {
 System.out.println("Enter string to reverse:");
 
 Scanner read = new Scanner(System.in);
 String str = read.nextLine();
 String reverse = "";
 
 
 for(int i = str.length() - 1; i >= 0; i--)
 {
 reverse = reverse + str.charAt(i);
 }
 
 System.out.println("Reversed string is:");
 System.out.println(reverse);
 }
}

首先,有一個更好的方法來反轉單詞。 但是讓我們看看你的程序。

我希望我的程序在新行上輸出每個單詞。

如果您想在新行中打印每個單詞,您可以將每個單詞添加到單詞列表中並在新行中打印每個單詞,或者您可以在每個單詞的末尾添加“\\n”。

還要注意窗簾中的字母“n”是如何丟失的,並且最后兩個單詞之間沒有空格。

這是因為endIndex開始於sentence.length()-1並且 Java 中的substring通過從 startIndex 提取到 endIndex - 1 來工作,即 endIndex 是獨占的,而 startIndex 是包括在內的。 您可以通過聲明endIndex = sentence.length()並從 i = sentence.length()-1迭代到0來修復它。

有了它,代碼將是:

public static void main(String[] args) {

    String sentence = new String("pay no attention to that man behind the curtain");
    String reversed = "";

    int endIndex = sentence.length();
    for(int i = sentence.length()-1; i >= 0; i--) {
        if(sentence.charAt(i) == ' ') {
            reversed += sentence.substring(i+1, endIndex) + "\n";
            endIndex = i;
        }
    }
    reversed += sentence.substring(0, endIndex);
    System.out.println(reversed);
  }

更好的方法是:

a) 將您的字符串轉換為字符數組

b) 然后反轉整個字符數組,它將變成:

niatruc eht dniheb nam taht ot noitnetta on yap

c) 然后原地反轉每個空格之間的字母。

d) 您將取回表示以下內容的新字符數組:

curtain the behind man that to attention no pay

並且您可以從新的字符數組構造一個字符串。

暫無
暫無

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

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