Pick random word from list? - c#

I´m having trouble picking a random word from a list in another file.
Actually I can´t even get it to choose any word. I´m not sure how to connect the 2 files so to say.
Hoping someone can help out, I´m a beginner so please explain as easy as possible:)
I have 2 files, one is called program.cs and the other is called WordList.cs
I´m gonna paste all my code but first the little snip that I´m having problem with. I just can´t figure out how to write the code correct.
Here is the little part which is called Pick word:
//PICK WORD
static string pickWord()
{
string returnword = "";
TextReader file = new StreamReader(words);
string fileLine = file.ReadLine();
Random randomGen = new Random();
returnword = words[randomGen.Next(0, words.Count - 1)];
return returnword;
}
And here is all the code in Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
class Hangman
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Title = "C# Hangman";
Console.WriteLine("Welcome To C# Hangman!");
//MENU
int MenuChoice = 0;
while (MenuChoice != 4)
{
Console.Write("\n\t1) Add words");
Console.Write("\n\t2) Show list of words");
Console.Write("\n\t3) Play");
Console.Write("\n\t4) Quit\n\n");
Console.Write("\n\tChoose 1-4: "); //Choose meny item
MenuChoice = Convert.ToInt32(Console.ReadLine());
WordList showing = new WordList();
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
showing.AddWord(insert);
Console.Write("\n\tList of words\n\n");
showing.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
showing.ListOfWords();
break;
case 3: //Running game
int numGuessesInt = -1;
while (numGuessesInt == -1)
{
/* Sets the number of guesses the user has to guess the word*/
pickNumGuesses(ref numGuessesInt);
}
/* Randomly picks a word*/
string word = pickWord();
/* Creates a list of characters that will show */
List<char> guessedLetters = new List<char>();
bool solved = false;
while (solved == false)
{
/* Displaying a string to the user based on the user's correct guesses.
* If nothing is correct string will return "_ _ _ " */
string wordToDisplay = displayWord(guessedLetters, word);
/* If the string returned contains the "_" character, all the
* correct letters have not been guessed, so checking if user
* has lost, by checking if numGuessesLeft is less than 1.*/
if (!wordToDisplay.Contains("_"))
{
solved = true;
Console.WriteLine("You Win! The word was " + word);
/* Check if the user wants to play again. If they do,
* then solved is set to true, will end the loop,
* otherwise, checkIfPlayAgain will close the program.*/
checkIfPlayAgain();
}
else if (numGuessesInt <= 0)
{
solved = true;
Console.WriteLine("You Lose! The word was " + word);
checkIfPlayAgain();
}
else
{
/* If the user has not won or lost, call guessLetter,
* display the word, minus guesses by 1*/
guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
}
}
break;
case 4:
Console.WriteLine("\n\tEnd game?\n\n");
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
}
}
// ****** PICK NUMBER OF GUESSES ******
static void pickNumGuesses(ref int numGuessesInt)
{
string numGuessesString = "";
Console.WriteLine("Pick a number of guesses");
numGuessesString = Console.ReadLine();
try
{
numGuessesInt = Convert.ToInt32(numGuessesString);
if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
{
throw new Exception();
}
}
catch (Exception)
{
numGuessesInt = -1;
Console.WriteLine("Error: Invalid Number of Guesses");
}
}
//PICK WORD
static string pickWord()
{
string returnword = "";
TextReader file = new StreamReader(words);
string fileLine = file.ReadLine();
Random randomGen = new Random();
returnword = words[randomGen.Next(0, words.Count - 1)];
return returnword;
}
// ****** Display word ******
static string displayWord(List<char> guessedCharacters, string word)
{
string returnedWord = "";
if (guessedCharacters.Count == 0)
{
foreach (char letter in word)
{
returnedWord += "_ ";
}
return returnedWord;
}
foreach (char letter in word)
{
bool letterMatch = false;
foreach (char character in guessedCharacters)
{
if (character == letter)
{
returnedWord += character + " ";
letterMatch = true;
break;
}
else
{
letterMatch = false;
}
}
if (letterMatch == false)
{
returnedWord += "_ ";
}
}
return returnedWord;
}
// ****** Guess letter ******
static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
{
string letters = "";
foreach (char letter in guessedCharacters)
{
letters += " " + letter;
}
Console.WriteLine("Guess a letter");
Console.WriteLine("Guessed Letters: " + letters);
Console.WriteLine("Guesses Left: " + numGuessesLeft);
Console.WriteLine(wordToDisplay);
string guess = Console.ReadLine();
char guessedLetter = 'a';
try
{
guessedLetter = Convert.ToChar(guess);
if (!Char.IsLetter(guessedLetter))
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("Error: Invalid Letter Choice");
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
bool repeat = false;
for (int i = 0; i < guessedCharacters.Count; i++)
{
if (guessedCharacters[i] == guessedLetter)
{
Console.WriteLine("Error: Invalid Letter Choice");
repeat = true;
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
}
if (repeat == false)
{
guessedCharacters.Add(guessedLetter);
numGuessesLeft -= 1;
}
}
// ****** Check to see if player wants to play again. ******
static void checkIfPlayAgain()
{
Console.WriteLine("Would you like to play again? (y/n)");
string playAgain = Console.ReadLine();
if (playAgain == "n")
{
Environment.Exit(1);
}
}
}
And here is the code for WordList.cs
using System;
using System.Collections.Generic;
class WordList
{
List <string> words = new List<string>();
public void ListOfWords()
{
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public void AddWord(string value){
words.Add(value);
}
}

I have made some changes to your code. The code works now but is far from perfect.
Your solution has two files Program.cs and Wordlist.cs, which looks like this
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
public class Hangman
{
/*
* Some notes on your code:
* use naming convention for methods and fields, i.e. methods names start with a capital letter
* use modifiers for methods, i.e private, public, protected in your method declarations
* make variables private if you use them on several methods
* and finally: read a book on c#
*
*/
private static WordList words;
private static Random randomGen = new Random();
public static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Title = "C# Hangman";
Console.WriteLine("Welcome To C# Hangman!");
initializeWordList();
//MENU
int MenuChoice = 0;
while (MenuChoice != 4)
{
Console.Write("\n\t1) Add words");
Console.Write("\n\t2) Show list of words");
Console.Write("\n\t3) Play");
Console.Write("\n\t4) Quit\n\n");
Console.Write("\n\tChoose 1-4: "); //Choose meny item
MenuChoice = Convert.ToInt32(Console.ReadLine());
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
words.Add(insert);
Console.Write("\n\tList of words\n\n");
foreach (string w in words) // Display for verification
Console.WriteLine(w);
break;
case 2:
Console.Write("\n\tList of words\n\n");
foreach (string w in words) // Display for verification
Console.WriteLine(w);
break;
case 3: //Running game
int numGuessesInt = -1;
while (numGuessesInt == -1)
{
/* Sets the number of guesses the user has to guess the word*/
pickNumGuesses(ref numGuessesInt);
}
/* Randomly picks a word*/
string word = PickWord();
/* Creates a list of characters that will show */
List<char> guessedLetters = new List<char>();
bool solved = false;
while (solved == false)
{
/* Displaying a string to the user based on the user's correct guesses.
* If nothing is correct string will return "_ _ _ " */
string wordToDisplay = displayWord(guessedLetters, word);
/* If the string returned contains the "_" character, all the
* correct letters have not been guessed, so checking if user
* has lost, by checking if numGuessesLeft is less than 1.*/
if (!wordToDisplay.Contains("_"))
{
solved = true;
Console.WriteLine("You Win! The word was " + word);
/* Check if the user wants to play again. If they do,
* then solved is set to true, will end the loop,
* otherwise, checkIfPlayAgain will close the program.*/
checkIfPlayAgain();
}
else if (numGuessesInt <= 0)
{
solved = true;
Console.WriteLine("You Lose! The word was " + word);
checkIfPlayAgain();
}
else
{
/* If the user has not won or lost, call guessLetter,
* display the word, minus guesses by 1*/
guessLetter(guessedLetters, word, wordToDisplay, ref numGuessesInt);
}
}
break;
case 4:
Console.WriteLine("\n\tEnd game?\n\n");
break;
default:
Console.WriteLine("Sorry, invalid selection");
break;
}
}
}
private static void initializeWordList()
{
words = new WordList();
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
}
// ****** PICK NUMBER OF GUESSES ******
private static void pickNumGuesses(ref int numGuessesInt)
{
string numGuessesString = "";
Console.WriteLine("Pick a number of guesses");
numGuessesString = Console.ReadLine();
try
{
numGuessesInt = Convert.ToInt32(numGuessesString);
if (!(numGuessesInt <= 20 & numGuessesInt >= 1))
{
throw new Exception();
}
}
catch (Exception)
{
numGuessesInt = -1;
Console.WriteLine("Error: Invalid Number of Guesses");
}
}
//PICK WORD
private static string PickWord()
{
return words[randomGen.Next(0, words.Count() - 1)];
}
// ****** Display word ******
private static string displayWord(List<char> guessedCharacters, string word)
{
string returnedWord = "";
if (guessedCharacters.Count == 0)
{
foreach (char letter in word)
{
returnedWord += "_ ";
}
return returnedWord;
}
foreach (char letter in word)
{
bool letterMatch = false;
foreach (char character in guessedCharacters)
{
if (character == letter)
{
returnedWord += character + " ";
letterMatch = true;
break;
}
else
{
letterMatch = false;
}
}
if (letterMatch == false)
{
returnedWord += "_ ";
}
}
return returnedWord;
}
// ****** Guess letter ******
static void guessLetter(List<char> guessedCharacters, string word, string wordToDisplay, ref int numGuessesLeft)
{
string letters = "";
foreach (char letter in guessedCharacters)
{
letters += " " + letter;
}
Console.WriteLine("Guess a letter");
Console.WriteLine("Guessed Letters: " + letters);
Console.WriteLine("Guesses Left: " + numGuessesLeft);
Console.WriteLine(wordToDisplay);
string guess = Console.ReadLine();
char guessedLetter = 'a';
try
{
guessedLetter = Convert.ToChar(guess);
if (!Char.IsLetter(guessedLetter))
{
throw new Exception();
}
}
catch (Exception)
{
Console.WriteLine("Error: Invalid Letter Choice");
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
bool repeat = false;
for (int i = 0; i < guessedCharacters.Count; i++)
{
if (guessedCharacters[i] == guessedLetter)
{
Console.WriteLine("Error: Invalid Letter Choice");
repeat = true;
//guessLetter(guessedCharacters, word, wordToDisplay, ref numGuessesLeft);
}
}
if (repeat == false)
{
guessedCharacters.Add(guessedLetter);
numGuessesLeft -= 1;
}
}
// ****** Check to see if player wants to play again. ******
static void checkIfPlayAgain()
{
Console.WriteLine("Would you like to play again? (y/n)");
string playAgain = Console.ReadLine();
if (playAgain == "n")
{
Environment.Exit(1);
}
}
}
Wordlist.cs
using System;
using System.Collections.Generic;
public class WordList : List<string>
{
}

Here is the very simple solution:
Populate your list just one time, or when ever you add any word, call this method. Code:
private void PopulateTheWordList()
{
Console.Write("\n\tAdd a word\n\n");
WordList.Add(Console.ReadLine());
}
Now just call this method to get random words:
private string PickWord()
{
Random ran = new Random();
return WordList[ran.Next(0, WordList.Count)];
}
If you need to create List of words in another class, then use keyword static:
static List<string> WordList = new List<string>();
Now you can call it by just writing the class name, like YourClassName.WordList

Try creating a Static Class and add a method for returning your List, you will then be able to access your wordlist.
example:
static class WordList
{
static List<string> words = new List<string>();
public static void ListOfWords()
{
words.Add("test"); // Contains: test
words.Add("dog"); // Contains: test, dog
words.Insert(1, "shit"); // Contains: test, shit, dog
words.Sort();
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
words.Add(value);
}
}
You would then change your switch statement to look something like this.
switch (MenuChoice)
{
case 1:
Console.Write("\n\tAdd a word\n\n");
var insert = Console.ReadLine();
WordList.AddWord(insert);
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
case 2:
Console.Write("\n\tList of words\n\n");
WordList.ListOfWords();
break;
....
and your pickWord Method would look like this:
static string pickWord()
{
string returnword = "";
Random randomGen = new Random();
returnword = WordList.GetWords()[randomGen.Next(0, WordList.GetWords().Count() - 1)];
return returnword;
}
I modified your Wordlist class so that it can use a file to maintain your Words between uses of your program, just incase that is what was being asked of you.
static class WordList
{
static string filePath = #"C:\temp\Word.txt";
static List<string> words = new List<string>();
private static void CheckFile()
{
//Makes sure our base words are saved to the file
if (!File.Exists(#"C:\temp\Word.txt"))
{
using (TextWriter writer = new StreamWriter(filePath))
{
writer.WriteLine("test");
writer.WriteLine("dog");
writer.WriteLine("shit");
}
}
}
public static void ListOfWords()
{
CheckFile();
words.Clear();
using (TextReader file = new StreamReader(filePath))
{
char[] delineators = new char[] { '\r', '\n' };
string[] tempWords = file.ReadToEnd().Split(delineators, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in tempWords)
{
words.Add(line);
}
}
foreach (string word in words) // Display for verification
{
Console.WriteLine(word);
}
}
public static List<string> GetWords()
{
return words;
}
public static void AddWord(string value)
{
CheckFile();
using (TextWriter writer = new StreamWriter(filePath,true ))
{
writer.WriteLine(value);
}
}
}

Related

Printing spaces between characters for answer to hangman game in C#

My apologies for asking yet another question, but I am struggling to get the desired output for my hangman program. When the user finds a correct letter, I would like it to display a space between letters and underscores; I can only get it to output a space after a letter and not between as desired. Also, when the secretword is guessed and the user wins, I would like the secret word to be output with spaces between the letters (eg. M A R I O). I have tried using +" " in various places, but still struggling to get the desired output. Any help would be greatly appreciated.
My code is as follows...
static void Main()
{
Console.Title = ("Hangman Game");
string[] secretWords = {
"mario", /*"sonic", "thelegendofzelda", "donkeykong", "luigi",
"peach", "link", "laracroft", "bowser", "kratos",
"playstation", "nintendo", "tetris", "grandtheftauto",
"finalfantasy", "thelastofus", "ghostoftsushima", "horizonzerodawn",
"halo", "forza", "crashbandicoot", "worldofwarcraft", "callofduty",
"fortnite", "animalcrossing", "doom", "metalgearsolid", "minecraft",
"residentevil", "pacman", "spaceinvaders", "asteroids",
"streetfighter", "mortalkombat", "supermariokart", "pokemon",
"bioshock", "tombraider"*/
};
Random R = new Random();
string secretword = secretWords[R.Next(secretWords.Length)];
List<string> letterGuessed = new List<string>();
int live = 5;
Console.WriteLine("Welcome To Hangman!");
Console.WriteLine("Enter a letter to guess for a {0} Letter Word", secretword.Length);
Console.WriteLine("You Have {0} Lives remaining \n", live);
Isletter(secretword, letterGuessed);
while (live > 0)
{
string input = Console.ReadLine();
if (letterGuessed.Contains(input))
{
Console.WriteLine("You Entered Letter [{0}] Already", input);
Console.WriteLine("Try a Different Letter \n");
continue;
}
letterGuessed.Add(input);
if (IsWord(secretword, letterGuessed))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(secretword);
Console.WriteLine("Congratulations!");
break;
}
else if (secretword.Contains(input))
{
Console.WriteLine("Good Entry\n");
string letters = Isletter(secretword, letterGuessed);
Console.Write(letters);
Console.WriteLine("\n");
}
else
{
Console.WriteLine("That Letter Is Not In My Word");
live -= 1;
Console.WriteLine("You Have {0} Lives Remaining", live);
}
Console.WriteLine();
if (live == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Game Over! \nMy Secret Word is [ {0} ]", secretword);
break;
}
}
Console.ReadKey();
}
static bool IsWord(string secretword, List<string> letterGuessed)
{
bool word = false;
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
word = true;
}
else
{
return word = false;
}
}
return word;
}
static string Isletter(string secretword, List<string> letterGuessed)
{
string correctletters = "";
for (int i = 0; i < secretword.Length; i++)
{
string c = Convert.ToString(secretword[i]);
if (letterGuessed.Contains(c))
{
correctletters += c;
}
else
{
correctletters += "_ ";
}
}
return correctletters;
}
}
}
Console.WriteLine(string.Join(" ", secretword.ToUpper().ToCharArray()));
worked as expected. Many thanks #41686d6564

Reading certain values from text document

This is my code, i am trying to figure out how to read an int value from a text document. eg. of text document: 1;Name;Surname;5 , I am trying to read only the last number, and can't figure out how to. I need to figure out a shorter solution, and a solution in general. Would apreciate any and all help you give me, programing advice, anything in general
struct redualnica
{
public int id;
public string ime;
public string priimek;
public int ocena;
public void vrednost(int d, string z, string m, int p)
{
id = d;
ime = z;
priimek = m;
ocena = p;
}
}
class Program
{
static void Main(string[] args)
{
string datoteka = "ocene.txt";
redualnica[] mojaredualnica = new redualnica[25];
int meni = 0;
do
{
Console.WriteLine("1. - Naloži podatke");
Console.WriteLine("2. - Izpiše vse podatke");
Console.WriteLine("3. - Izpišite določene ocene");
Console.WriteLine("4. - Izhod");
meni = Convert.ToInt32(Console.ReadLine());
switch (meni)
{
case 1:
Nalozi(mojaredualnica, datoteka);
break;
case 2:
Izpis(mojaredualnica);
break;
case 3:
Izpis(doloceneocene);
break;
default:
meni = 0;
break;
}
} while (meni != 0);
}
static void Nalozi(redualnica[] mG, string dat)
{
StreamReader sr = File.OpenText(dat);
string vrstica = sr.ReadLine();
string[] tposameznihpodatkov;
int i = 0;
while (vrstica != null)
{
tposameznihpodatkov = vrstica.Split(';');
mG[i].id = Convert.ToInt32(tposameznihpodatkov[0]);
mG[i].ime = tposameznihpodatkov[1];
mG[i].priimek = tposameznihpodatkov[2];
mG[i].ocena = Convert.ToInt32(tposameznihpodatkov[3]);
vrstica = sr.ReadLine();
i++;
}
sr.Close();
}
static void Izpis(redualnica[] mG)
{
Console.WriteLine("----------------------");
foreach (var x in mG)
{
Console.WriteLine(x.id + " " + x.ime + " " + x.priimek + ", " + x.ocena);
}
Console.WriteLine("----------------------");
}
static void izbira(int a)
{
a = int.Parse(Console.ReadLine());
}
static void dodajdijaka(int b)
{
using (StreamWriter sr = File.AppendAllText(path))
{
string st = "";
sr.WriteLine(st = sr.ReadLine());
}
}
}
I input an id;name;surname;number
In this format, and it has to read and write only last number
I am looking your code, but it is not clear!. I would like to some advice, maybe this will fix your code problem.
I edit Nalozi method. I notice,while condition would throw exception.
static void Nalozi(redualnica[] mG, string dat)
{
StreamReader sr = File.OpenText(dat);
string[] tposameznihpodatkov;
int i = 0;
while (sr.EndOfStream && i <= mG.Length)
{
string vrstica = sr.ReadLine();
tposameznihpodatkov = vrstica.Split(';');
mG[i].id = Convert.ToInt32(tposameznihpodatkov[0]);
mG[i].ime = tposameznihpodatkov[1];
mG[i].priimek = tposameznihpodatkov[2];
mG[i].ocena = Convert.ToInt32(tposameznihpodatkov[3]);
vrstica = sr.ReadLine();
i++;
}
sr.Close();
}

Check ReadKey only for letters (alphabet) in string

i am doing game "Hangman" but i have a problem. I am using ReadKey to find the guess of player, but he can use even numbers or buttons like "Enter" etc. I want to stop this, but i don't know how :/ Can you help me please? I want control, if in result of ReadKey is letter from alphabet or no (but it must be in "string" format, cuz i am working later with string). Thank you very much guys, here is my code :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Hangman
{
class MainClass
{
/// <summary>
/// Hra Oběšenec
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Console.WriteLine("Vítejte ve hře Oběšenec!");
//List slov, které bude hráč hádat
string[] words = new string[5];
words[0] = "car";
words[1] = "school";
words[2] = "apple";
words[3] = "orange";
words[4] = "xamarin";
//Získávám délku slova (hádaného slova)
for (int X = 0; X < words.Length; X++)
{
string guessWord = words[X];
short lifes = 5;
short guessedLetters = 0;
char GuessingLetter;
char[] lettersOfWord = new char[guessWord.Length];
//
for (int I = 0; I < guessWord.Length; I++)
{
//Length of word is changing to *
lettersOfWord[I] = '*';
}
bool InGame = true;
//When this while is true, the game is still going, when it will be false, the game will end
while (InGame)
{
//Ochrana proti špatnému inputu
try
{
Console.WriteLine(lettersOfWord);
Console.WriteLine("Stiskněte klávesu. Životy:" + lifes);
ConsoleKeyInfo result_guess = Console.ReadKey(true);
string result = result_guess.KeyChar.ToString();
if (result.Length == 0)
{
continue;
}
//Hráč hádá slovo
GuessingLetter = result[0];
lifes--;
for (int I = 0; I < lettersOfWord.Length; I++)
{
if (lettersOfWord[I] == '*')
{
//Pokud hráč uhádne písmenko ve slově
if (guessWord[I] == GuessingLetter)
{
lettersOfWord[I] = GuessingLetter;
guessedLetters++;
lifes++;
Console.WriteLine("Správně!");
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Nastala neočekávaná chyba!" + e);
}
//Pokud prohraje(promrhá všechny pokusy) hra skončí, avšak pokud slovo uhádne (a zůstane alespoň jeden život) vyhrál hru
if (lifes== 0 || guessedLetters == guessWord.Length)
{
//Konec hry
InGame = false;
if (lifes == 0)
{
Console.WriteLine("Smůla prohrál jsi!");
Console.ReadKey();
break;
}
else
{
//Vítězství nad levlem
Console.WriteLine("Uhodnul jsi celé slovo! Gratuluji!!");
}
}
}
}
}
}
}
Check if the keychar is a letter with the IsLetter method and keep asking for letters if it doesn't. Something like this:
private char GetLetter()
{
while (true)
{
Console.WriteLine("Please input a letter.");
var character = Console.ReadKey().KeyChar;
if (char.IsLetter(character))
return character;
}
}

How to replace each 3rd or 4th character in a string with a newline? C#

For instance I've got this string: "Is it allowed to enter this room without asking?"
I'd like to place each 3rd or 4th ' ' a newline to get it to be like: "Is it allowed to(newline)enter this room without(newline)without asking?"
Here's a very verbose solution, based on the assumption that each word is separated by others only with a space.
var splitted = "Is it allowed to enter this room without asking?".Split(' ');
StringBuilder str = new StringBuilder();
int i = 1;
foreach (var word in splitted)
{
str.Append(word);
if (i % 3 == 0)
{
str.Append(System.Environment.NewLine);
}
else
{
str.Append(" ");
}
i++;
}
var result = str.ToString();
static void Main(string[] args)
{
const string text = "Is it allowed to enter this room without asking?";
string newText = null;
int count = 0;
foreach (char c in text)
{
string temp = c.ToString();
if (c == ' ')
{
count ++;
bool placeNewLine = false;
Random random = new Random();
if (random.Next(0, 2) == 1) placeNewLine = true;
if (count == 4 || (placeNewLine && count ==3))
{
temp = Environment.NewLine;
count = 0;
}
}
newText += temp;
}
Console.WriteLine(newText);
Console.ReadLine();
}

PigLatin translate

I will create a program that translates English words into Pig Latin ... My problem with the code found below, is that the only word in the last index of the array as reported in the results? Does anyone see the error?
Thanks in advance
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnTrans_Click( object sender, EventArgs e )
{
string engWordText = engWord.Text.ToString();
string let1;
string restLet;
int position;
string pigLatin = "";
string vokal = "AEIOUaeiou";
// split the sentence into individual words
//string[] words = engWordText.Split(' ');
string[] transWord = engWordText.Split(' ');
// translate each word into pig latin
foreach (string word in transWord)
{
// check for empty TextBox
try
{
let1 = word.Substring(0, 1);
restLet = word.Substring(1, word.Length - 1);
position = vokal.IndexOf(let1);
if (position == -1)
{
pigLatin = restLet + let1 + "ay";
}
else
{
pigLatin = word + "way";
}
// display the translation
latinInput.Text = pigLatin.ToString();
engWord.Clear();
}
catch (System.ArgumentOutOfRangeException)
{
MessageBox.Show("Du måste skriva in ett engelskt ord", "PigLatin",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
} // end method translateButton_Click
// pressing enter is the same as clicking the Translate Button
private void engWordText_KeyDown( object sender, KeyEventArgs e )
{
// allow user to press enter in TextBox
if ( e.KeyCode == Keys.Enter )
btnTrans_Click( sender, e );
} // end method inputTextBox_KeyDown
} // end class PigLatinForm
You are assigning the value of pigLatin to the text box's Text property at the end of each loop, which means it will only have the last value that was assigned to it. Try this:
List<string> plWords = new List<string>();
// translate each word into pig latin
foreach (string word in transWord)
{
// check for empty TextBox
try
{
let1 = word[0];
restLet = word.Substring(1, word.Length - 1);
if (!vokal.Contains(let1))
{
pigLatin = restLet + let1 + "ay";
}
else
{
pigLatin = word + "way";
}
plWords.Add(pigLatin);
}
catch (System.ArgumentOutOfRangeException)
{
MessageBox.Show("Du måste skriva in ett engelskt ord", "PigLatin",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
engWord.Clear();
latinInput.Text = string.Join(" ", plWords.ToArray());
As a bit of a bonus, here's how you can make this operation quite a bit cleaner using Linq:
private static string MakePigLatin(string word)
{
const string vowels = "AEIOUaeiou";
char let1 = word[0];
string restLet = word.Substring(1, word.Length - 1);
return vowels.Contains(let1) ? word + "way" : restLet + let1 + "ay";
}
private void btnTrans_Click( object sender, EventArgs e )
{
var plWords = engWord.Text
.Split(new[]{' '}, StringSplitOptions.RemoveEmptyEntries)
.Select(MakePigLatin);
latinInput.Text = string.Join(" ", plWords);
engWord.Clear();
}

Categories

Resources