Newbie
Newbie

Reputation: 179

How to Turn a Randomized String Array 'word' into an array made up of the string's Characters C#?

Okay, so I'm creating a hang-man game (Lame, I know, but I gotta' start somewhere). I have successfully pulled ~30 random words from a text file into a variable and can properly display the word in a random order onto the screen (just to test and make sure the variable is obtaining a whole word in random order).

But I need to take that string and break it into single characters in order to 'blank' out the letters to be 'guessed' by the user. I assume an array is the best way to do this - coupled with a while loop that will run while the character != 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();


    }


  }
}

I'm open to references in order to figure it out myself, but I'm kinda' stuck here.

Also, how do I close the file that I've opened so that it can be accessed later on in the program if need be? I've only learned the StreamReader("filename") way of 'variable.Close();' - but that isn't working here.

Edit

And why someone would vote this question down is beyond me. lol

Upvotes: 0

Views: 80

Answers (4)

Newbie
Newbie

Reputation: 179

Thanks to Sven, I was able to figure it out and I was able to add some things onto it as well!! I'm posting this for other newbs to understand from a newb's perspective:

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

    }


  }
}

Upvotes: 0

James Buck
James Buck

Reputation: 1640

You can simplify your code a bit as follows. Previously your activeWord variable was an integer and therefore cannot be converted to a character array.

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();
}

However a string in C# can be treated as an enumerable object and therefore you should only be using a character array if you need to mutate parts of the string.

Upvotes: 0

Sven Grosen
Sven Grosen

Reputation: 5636

A couple of points here (first of all, you are off to a great start):

  1. You are needlessly re-reading your file to get the line count. You can use myWordArrays.Length to set your lineCount variable
  2. Regarding your question about closing the file, per MSDN File.ReadAllLines() closes the file after it is done reading it, so you are fine there with what you already have.

A string itself can be treated like an array in terms of accessing by index and accessing its Length property. There's also the ability to iterate over it implicitly like so:

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

Upvotes: 1

Andrey Korneyev
Andrey Korneyev

Reputation: 26846

You can access any character in the string by its index, so you can think of string as array of chars:

For example, like this snippet:

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

Upvotes: 1

Related Questions