为了账号安全,请及时绑定邮箱和手机立即绑定

如何获取字符串中两个相同字符的索引?

如何获取字符串中两个相同字符的索引?

C#
白衣非少年 2022-01-09 16:31:19
我想创建简单的控制台僚机游戏。我的错误是,如果我尝试在单词中获取 2 个相同字符的 pos,我只会得到一个,而另一个被跳过。例如西红柿。控制台输出:番茄_ 奥马特 _ _我知道我没有使用 live 没有时间我做它层。类程序{   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!");            }        }    }    }
查看完整描述

1 回答

?
蝴蝶不菲

TA贡献1810条经验 获得超4个赞

您需要处理可能是不同大小写等的用户输入。因此,最简单的方法是只访问随机单词中的每个字符一次。


这是我为解决此问题而制作的 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


查看完整回答
反对 回复 2022-01-09
  • 1 回答
  • 0 关注
  • 246 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号