【问题标题】:How to Turn a Randomized String Array 'word' into an array made up of the string's Characters C#?如何将随机字符串数组“单词”转换为由字符串的字符 C# 组成的数组?
【发布时间】:2015-07-22 14:45:43
【问题描述】:

好的,所以我正在创建一个刽子手游戏(跛脚,我知道,但我必须从某个地方开始)。我已经成功地将大约 30 个随机单词从文本文件中提取到一个变量中,并且可以在屏幕上以随机顺序正确显示该单词(只是为了测试并确保该变量以随机顺序获取整个单词)。

但我需要将该字符串分解为单个字符,以便“删除”用户“猜测”的字母。我认为数组是做到这一点的最佳方式——再加上一个 while 循环,该循环将在字符 != null 时运行。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hangman
{
class Program
{
    static void Main(string[] args)
    {
        String[] myWordArrays = File.ReadAllLines("WordList.txt");
        Random randomWord = new Random();
        int lineCount = File.ReadLines("WordList.txt").Count();            
        int activeWord = randomWord.Next(0, lineCount);

        /*CharEnumerator activeWordChar = activeWord; --- I have tried this, 
        but it says "Cannot implicitly convert type 'int' to 'System.CharEnumerator' 
        --- while redlining "activeWord." */

        /*CharEnumerator activeWordChar = activeWord.ToString 
        -- I have tried this but it says "Cannot convert method group 'ToString' to 
        non-delegate type 'System.CharEnumerator'. Did you intend to invoke the method?

         I also tried moving the declaration of activeWordChar below the 'writeline' 
         that displays the word properly to the console. 

         I have even tried to create a Char[] activeWordChar = activeWord.toCharArray; But this doesn't work either. 
         */            

        //I'm using this writeline "the word for this game is: " ONLY to test that the 
        //system is choosing random word **end comment

        Console.WriteLine("The Word for this game is: " + myWordArrays[activeWord]);



        //Console.WriteLine("The Characters are like this: " + activeWordChar[]); 
        //my attempt at printing something, but it doesn't work. :(
        Console.ReadLine();


    }


  }
}

我愿意参考参考资料以便自己弄清楚,但我有点卡在这里。

另外,如果需要,我如何关闭我打开的文件,以便以后可以在程序中访问它?我只学习了 'variable.Close();' 的 StreamReader("filename") 方式- 但这在这里行不通。

编辑

为什么有人会否决这个问题,这超出了我的理解。哈哈

【问题讨论】:

  • var chars = "abcd".ToArray();
  • 但是单词是随机选择的,单词的长度不等。我不知道要移动到数组中的“单词” - 如果它在元素 myWordArrays[activeWord] 中,我似乎只能让 activeWord 充当“写入控制台”
  • myWordArrays[activeWord].ToArray() :)
  • 对于 .Close() 的第二个问题,请改用 using 语句。它基本上在 using 语句中保持文件打开。 msdn.microsoft.com/en-us/library/yh598w02.aspx
  • @thinklarge - 谢谢。

标签: c# arrays string char


【解决方案1】:

这里有几点(首先,你有一个很好的开始):

  1. 您不必要地重新读取文件以获取行数。您可以使用myWordArrays.Length 设置您的lineCount 变量
  2. 关于您关于关闭文件的问题,MSDN File.ReadAllLines() 会在文件读取完成后关闭文件,因此您可以使用已有的文件。

就按索引访问和访问其Length 属性而言,可以将字符串本身视为数组。还可以像这样隐式地迭代它:

foreach (char letter in myWordArrays[activeWord])
{
// provide a blanked-out letter for each char
}

【讨论】:

  • 太棒了,先生。太奇怪了——我知道我在某个时候尝试过 myWordArrays.Length ,但无论出于何种原因它都不起作用。哈哈。所以基本上,我现在可以摆脱整个 lineCount 变量了。 :) 关于 foreach 的问题:(字符字母...)中的“字母”是您创建的变量吗?或者它是 c# 中的一种实际类型的东西?
  • letter 只是在 foreach 闭包中创建的变量。它只会存在于那些大括号内。
  • 非常酷。我刚刚使用它并且它有效,但是当它显示到控制台时,我得到 f_(然后在新行)o_(新行)r_(换行)t_ - 这个词是堡垒。哈哈。现在我需要弄清楚如何用空格替换每个字母。不过不要告诉我。伊玛试图自己解决这个问题。非常感谢!!!!
  • @Newbie 一个提示:除了Console 上的WriteLINE() 之外,还有其他方法可以解决您的(换行符)问题....
  • 是的,所以我想通了。我正在做 WriteLine 只是因为我已经习惯了,而且我正在连接每个“字母”+“”,所以我只是删除了字母并保留了“”。另外,我使用的是 Console.Write() ,这样它就不会每次都换行。谢谢你没有放弃它。另外,我现在有我的程序,它将实际读取单词的长度并询问“你能猜出这个'x'字母单词是什么吗”并且长度正确显示!惊人的!哈哈。如此愚蠢的程序值得骄傲,但它对我来说是纯粹的。 :) 再次感谢!
【解决方案2】:

您可以通过其索引访问字符串中的任何字符,因此您可以将字符串视为字符数组:

比如像这样sn-p:

string word = "word";
char w1 = word[0];
Console.WriteLine(w1);

【讨论】:

  • 是的,但是单词是随机选择的,因此我不知道每个数组有多少元素。我是否必须先以某种方式获取 arrayVariable.Length,然后分别引用每个元素?
  • @Newbie 每个字符串都有其长度,由Length 属性指定。在我发布的截图中,word.Length 将返回其精确长度 4。所以从这个角度来看,它与数组非常相似。如果你需要“真正的”char[] 对象,你可以使用String.ToCharArray 方法。
  • 对,但是为了给每个字母写空格,我需要知道要写多少元素,对吧?或者我可以只做 Console.WriteLine(myWordArray[activeWord].length) 吗?
  • @Newbie 好吧,如果您只需要输出包含空格并具有精确长度的字符串,您可以使用适当的构造函数来获取符号重复和重复计数:Console.WriteLine(new String(' ', myWordArray[activeWord].Length));
  • 谢谢。事实上,这正是我在“foreach”循环之后显示单词中字母数量的方法,以便为每个字母表示显示下划线。谢谢!!
【解决方案3】:

您可以按如下方式简化代码。以前您的 activeWord 变量是整数,因此无法转换为字符数组。

static void Main(string[] args)
{
    String[] myWordArrays = File.ReadAllLines("WordList.txt");
    Random random = new Random();           
    string activeWord = myWordArrays[random.next(myWordArrays.Length)];
    char[] chars = activeWord.ToCharArray();
}

但是,C# 中的字符串可以被视为可枚举对象,因此只有在需要更改字符串的某些部分时才应该使用字符数组。

【讨论】:

  • 我已经尝试过了,但它说它不能隐式地将 int 转换为字符串 - 它说 activeWord 自动是一个 int (这就是为什么我将它声明为 int 开始)。 ??
【解决方案4】:

多亏了 Sven,我才能够弄清楚,并且还能够在上面添加一些东西!!我发布这个是为了让其他新手从新手的角度理解:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hangman
{
class Program
  {
    static void Main(string[] args)
    {
        printWord();                                          


    }

    /*I created a method to perform this, so that I can have the program stay open for 
    either 1) a new game or 2) just to see if I could do it. It works!*/

    private static void printWord()
    {
        String[] myWordArrays = File.ReadAllLines("WordList.txt");
        Random randomWord = new Random();
        //int lineCount = File.ReadLines("WordList.txt").Count();

        //The line below fixed my previous issue of double-reading file            
        int activeWord = randomWord.Next(0, myWordArrays.Length);

        string userSelection = "";

        Console.WriteLine("Are you Ready to play Hangman? yes/no: ");
        userSelection = Console.ReadLine();
            if(userSelection == "yes")
            {
                /*This runs through the randomly chosen word and prints an underscore in 
                place of each letter - it does work and this is what fixed my 
                previous issue - thank you Sven*/

                foreach(char letter in myWordArrays[activeWord])
                {
            Console.Write("_ ");

                }

                //This prints to the console "Can you guess what this 'varyingLength' letter word is?" - it does work.
                Console.WriteLine("Can you guess what this "+ myWordArrays[activeWord].Length +" letter word is?");
                Console.ReadLine();
            } 
            //else if(userSelection=="no") -- will add more later

    }


  }
}

【讨论】:

    猜你喜欢
    • 2013-11-27
    • 1970-01-01
    • 2017-05-20
    • 2016-05-22
    • 1970-01-01
    • 2016-11-20
    • 2021-12-13
    • 2017-11-27
    相关资源
    最近更新 更多