簡體   English   中英

如何在Java中將每個單詞與字符串分開?

[英]How to separate each word from a string in java?

我的AP項目之一包括將每個單詞與字符串分開,我嘗試完成無數次卻沒有成功! 我的課尚未學習數組,正則表達式或拆分,因此,如果可以幫助您,請避免其中任何一種。 但是我們確實學習了子字符串,charAt,indexOf,length,trim ...

這是我的嘗試之一:(請注意,為了讓我真正注意到我已經拆分了它們,我嘗試在要重新創建的字符串中添加N ,即newWord)

public class Functions {
public static String stringReversal(String word){
    if (word.length() <= 1){
        return word;
    }else{
        char c = word.charAt(0);
        return stringReversal(word.substring(1)) + c;
    }
}

public static Boolean palindrome(String word){
    Boolean palindrome;
    if (word.equalsIgnoreCase(stringReversal(word))){
        return palindrome = true;
    } else{
        return palindrome = false;
    }
}

public static String pigLatin(String sentence){
    if(sentence.length() <= 1){
        return sentence;
    } else {
       String newWord = "";
       return newWord += pigLatin(sentence.substring(0, sentence.indexOf(" "))) + " N ";
    }
}

}

主要:

public class Main {
public static void main (String [] args){
    Scanner in = new Scanner(System.in);
    String word = in.nextLine();
    System.out.println(Functions.test(word));
   }
} 

但是,輸出僅打印N 任何人都可以請幫助並顯示出可以實現此目標的方法嗎?我嘗試了很多想法,但都沒有奏效。

由於這似乎與家庭作業密切相關,因此我僅會發布一些提示和建議,您將不得不結合我的提示和建議以自己提出解決方案。

我相信這是: sentence.indexOf("")應該是這樣的: sentence.indexOf(" ")

檢查一個空字符串的indexOf沒有多大意義(它總是返回零,因為空字符串可以在String中的任何地方找到)。

public static void main(String[] args) {
    String word = "a bit of words";
    System.out.println(test(word));
}

public static String test(String sentence){
    if(sentence.length() <= 1){
        return sentence;
    } else {
        String newWord = "";
        return newWord += test(sentence.substring(0, sentence.indexOf(" "))) + " N ";
    }
}

上面的照片: a N

但是,如果您的輸入只有一個單詞,則sentence.indexOf(" ")將返回-1。 您將需要檢查。 建議:修改您的if語句,以檢查字符串是否包含空格字符。

要解決分配問題,您將需要某種循環(遞歸也可以是一種循環),以便對每個單詞重復稍作修改的過程。 提示:獲取第一個單詞,然后獲取原始字符串(提取的單詞除外)。

public static void main( String[] args )
{
    Scanner in = new Scanner( System.in );
    try
    {
        while( true )
        {
            String word = in.nextLine();
            System.out.println( splitWords( word ) );
        }
    }
    finally
    {
        in.close();
    }

}

private static String splitWords( String s )
{
    int splitIndex = s.indexOf( ' ' );
    if( splitIndex >= 0 )
        return s.substring( 0, splitIndex ) + " N " + splitWords( s.substring( splitIndex + 1 ) );
    return s;
}

您可以使用標准方法String#split()

String[] words = sentence.split(' ');

注意比單詞是一個數組

暫無
暫無

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

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