簡體   English   中英

檢查用戶輸入的字符串是否包含相同的字母

[英]Check if user input strings contain the same letters

如何檢查用戶通過掃描儀輸入的字符串(用戶可以選擇他想輸入多少個單詞)是否包含相同的字母? 假設用戶輸入以下 3 個單詞:

比賽自行車電腦

此示例中的每個單詞都包含“e”和“c”。 如何比較這些字符串並在新字符串中保護結果(e 和 c)?

public class Comparison {


public static void main(String[] args) {

    String letters = "";


    Scanner input = new Scanner(System.in);
    System.out.println("How many words do you want to type in?:");
    count = input.nextInt();

    String[] words= new String[count];


    for (int i = 0; i < words.length; i++) {
        if (words[i].charAt(0) == words[j].charAt(0)) {
            letters = letters + words[i].charAt(j);
        }
}
}

這里需要幾件。

  1. 使用掃描儀從用戶那里獲取單詞。 你不是在問那個。 這個想法是提示,讀入輸入,並生成一個字符串數組。 一種方法可能是使用 split 方法。 你不是在問這部分。 你問一旦你有了這個字符串數組該怎么辦。 要測試其他部分,您可以使用傳遞給 main 的 args,然后開發此部分。

  2. 一種僅在兩個字符串之間查找公共字母的方法。 您表示您有這種方法有效。 所以我不打算分享。 讓我們想象一下它的樣子:

    /**

    • 方法 findCommonLetters *
    • @param word1 第一個詞
    • @param word2 第二個詞
    • @return 一個包含兩個單詞中常見字母的字符串,不重復 */

    public String findCommonLetters(String word1, String word2) { //你的代碼在這里 }

  3. 一種獲取任意長度的字符串數組並獲取所有字母的共同點的方法。 這就是你所要求的。 假設您具有 2 中描述的方法,這是一種方法。 這個想法是一次只處理 2 個,並且只在下一個單詞中尋找到目前為止所有單詞中共有的字母(並循環直到我們處理完所有單詞)。 代碼如下:

    /**

    • 方法 findCommonLetters *
    • @param words 一個單詞數組
    • @return 包含所有單詞的字母的字符串 */

公共字符串 findCommonLetters(String[] words)

 {
            if (words.length == 0) {
                return ""; //there are no letters
            } else if (words.length == 1) {
                //if the desired behavior is as I do here, this else if block could go away
                return words[0]; //trivially all the words have the same letters
            } else {
                String result = words[0]; // first word
                for (int i = 1; i < words.length; i++) {
                    result = findCommonLetters(result, words[i]); //find letters in common between all words processed so far and next word
                    //if you want, you could break here if result is empty
                }
                return result;
            }
        }

將這三個部分放在一起將產生預期的結果。

假設 3 個單詞 s1, s2, s3 其中 s1 是最小的字符串,並且新的字符串將攜帶這些單詞上的重復字符,稱為重復字符。

String repeatedChars=" ";

for(int i=0 ; i < s1.length() ; i++)
{

for(int j=0 ; j < s2.lenght() ; j++)
{

if(s1[i] == s2[j])
{

for(int k=0 ; k < s3.length() ; k++)
{

if(s2[j] == s3[k])
repeatedChars += s3[k];

}
}
}
}

目前我們有包含重復字符的字符串,您可以通過任何方式拆分每個字符

暫無
暫無

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

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