簡體   English   中英

如何獲取字符串中兩個相同字符的索引?

[英]How can i get index of two same character in string?

我想創建一個簡單的控制台wingman game。我的錯誤是,如果我嘗試在單詞中獲得2個相同字符的pos,我只會得到一個而另一個會被跳過。 例如Tomatoe。

控制台輸出:

番茄(Tomatoes)

_麥芽_ _

我知道我沒有使用直播,沒有時間去做。

課程計划{

   static string[] word = { "Pineapple", "Apple" , "Tomatoe" , "Pizza"};

    static int wordIndex = 0;

    static char[] randomWord;

    static bool guessing = true;

    public static void Main(string[] args)

    {
        int lives = 3;
        Console.OutputEncoding = Encoding.UTF8;
        Console.InputEncoding = Encoding.UTF8;
        Random r = new Random();
        wordIndex = r.Next(word.Length);
        randomWord = word[wordIndex].ToLower().ToCharArray();
         char[] randomWordcensored = new char[randomWord.Length];
        for (int i = 0; i < randomWord.Length; i++)
        {
            randomWordcensored[i] = '_';
        }
        Console.WriteLine("Hello");
        foreach (var item in randomWordcensored)
        {
            Console.Write(item + " ");
        }
        Console.WriteLine();
        Console.WriteLine("Please Enter character:");

        while (guessing = true)
        {
            int g = 0;
            char userinput;
            bool security = char.TryParse(Console.ReadLine() ,out userinput);
            if (security == true) { 

            if (randomWord.Contains(userinput))
            {        //help needed
                    g = (word[wordIndex].ToString().IndexOf(userinput) == -1  ? 0 : word[wordIndex].ToString().IndexOf(userinput));
                    randomWordcensored[g] = userinput;
                Console.WriteLine("Good :) " + g);
                    foreach (var item in randomWordcensored)
                    {
                        Console.Write(item + " ");
                    }
            }

            else
            {
                    lives--;
                Console.WriteLine("Wrong!\n-Lives:" + lives);

            }

        }
            else
            {
                Console.WriteLine("Enter only one charracter!");
            }
        }

    }


    }

您將需要處理可能與大小寫不同的用戶輸入。 因此,最簡單的方法是只訪問隨機單詞中的每個字符一次。

是我為解決此問題而制作的REPL

using System;
using System.Collections.Generic;

class MainClass {
    public static void Main (string[] args) {
        var word = "Tomato";
        var input = "t";
        var letter = input.ToLower()[0];

        var indices = new List<int>();
        for(var i = 0; i < word.Length; i++)
            if (word.ToLower()[i] == letter)
                indices.Add(i);

        Console.WriteLine($"Secret word: {word}");
        Console.WriteLine($"User guess: {input}");
        Console.WriteLine($"Found at {String.Join(", ", indices)}");
    }
}

及其輸出:

Mono C# compiler version 4.0.4.0
Secret word: Tomato
User guess: t
Found at 0, 4

暫無
暫無

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

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