How can i get index of two same character in string? - c#

I want to create simple console wingman game.My error is that if i try get pos of 2 same character in word i get only one and the other is skipped.
For example Tomatoe.
Console output:
Tomatoe
_ o m a t _ _
I know i didnt use live didnt have time for that i do it layter.
class Program {
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!");
}
}
}
}

You'll want to handle user input that might be different casing and such. Because of that it's easiest to just visit every character in the random word just once.
Here's a REPL that I made to solve this:
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)}");
}
}
and its output:
Mono C# compiler version 4.0.4.0
Secret word: Tomato
User guess: t
Found at 0, 4

Related

Using an array of random words in C# [duplicate]

This question already has answers here:
Retrieving a random word from a string array [duplicate]
(2 answers)
Closed 2 years ago.
Good evening.
I am trying to create a hangman game in C#. It works fine when I use just one secret word (In this example, the word HASHTAG is used).
But I need to get it to work using an array of words as per those featured in the multi-line comments.
Can anyone please offer assistance?
My full code follows...
class HangManGame
{
static void Main()
{
Console.Title = ("Hangman Game");
string secretword = "HASHTAG";
/*string[] secretword = {
"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"
}; */
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");
GetAlphabet(input);
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;
}
static void GetAlphabet(string letters)
{
List<string> alphabet = new List<string>();
for (int i = 1; i <= 26; i++)
{
char alpha = Convert.ToChar(i + 96);
alphabet.Add(Convert.ToString(alpha));
}
int num = 49;
Console.WriteLine("Letters Left are :");
for (int i = 0; i < num; i++)
{
if (letters.Contains(letters))
{
alphabet.Remove(letters);
num -= 1;
}
Console.Write("[" + alphabet[i] + "] ");
}
Console.WriteLine();
Console.WriteLine("\n");
}
}
}
Implementation of 'Honeyboy Wilson' comment
Random random = new Random();
string secretword = secretwords[random.Next(0, secretwords.Length)];
Switch the declaration order and use the Random class to pick a value from the Array?
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)];

Reversed chars - foreach loop

I want to print the 3 lines of characters in reversed order but this example is done simply. How can I do it with foreach loop without using arrays?
public static void Main()
{
char firstInput = char.Parse(Console.ReadLine());
char secondInput = char.Parse(Console.ReadLine());
char thirdInput = char.Parse(Console.ReadLine());
Console.WriteLine(thirdInput.ToString() + " " + secondInput.ToString() + " " + firstInput.ToString());
}
You could create a method using the params keyword - not tested but something like:
private static string ReverseOrder(params char[] characters)
{
var result = "";
for (int i = characters.count; i > 0; i--)
{
result = result + characters[i];
}
return result;
}
and call like:
var reverseOrderResult = ReverseOrder(firstinput, secondinput, thirdinput);
Here's an attempt to follow the input conditions: no arrays and use of foreach loop (I'm sure the author isn't looking for something like this)
static void Main()
{
var result = "";
foreach (var c in NextInput(3))
{
result = c + " " + result;
}
Console.WriteLine(result);
}
private static IEnumerable<char> NextInput(int count)
{
var i = 0;
while (i++ < count)
yield return char.Parse(Console.ReadLine());
}

English to Pig Latin C# Console Application

I'm having some trouble making an applicaton in c# converting english to pig latin. I have everything else down except for when it comes to making the getTranslation method for it. For some odd reason I just can't figure it out. IF someone could give me some ideas I would appreciate it.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace W15M5A2_CPigLatinApp
{
class W15M5A2_CPigLatinAppProgram
{
static void Main(string[] args)
{
string inputPhrase = "";
string[] phraseOut;
DisplayInfo();
inputPhrase = GetPhrase();
while (inputPhrase != "")
{
Console.WriteLine(" ");
phraseOut = GetTranslation(inputPhrase);
DisplayResults(inputPhrase, phraseOut);
inputPhrase = GetPhrase();
}
Console.ReadKey();
}
public static void DisplayInfo()
{
Console.WriteLine("********************************************************" +
"\n*** You will be prompted to enter a string of ***" +
"\n*** words. The phrase will be converted into a ***" +
"\n*** pseudo Pig Latin with results displayed. ***" +
"\n\n*** Enter as many strings as you would like. ***" +
"\n********************************************************\n\n");
Console.Write("\n\n\n Press any key when you are ready to begin...");
Console.ReadKey();
Console.Clear();
}
public static string GetPhrase()
{
string inputPhrase;
Console.WriteLine("Enter a phrase or group of words " +
"\nTo Exit, press the Enter key\n");
inputPhrase = Console.ReadLine();
return inputPhrase;
}
// GetTranslation method
public static string[] GetTranslation(string phraseIn)
{
}
public static void DisplayResults(string input, string[] output)
{
Console.Clear();
Console.WriteLine("Original Phrase: " + input + "\n");
Console.Write("\nNew Phrase: ");
foreach (string i in output)
{
Console.Write(i + " ");
}
Console.WriteLine("\n");
}
}
}
public static string[] GetTranslation(string phraseIn)
{
string vow = "aeiouyAEIOUY";
var splitted = phraseIn.Split(new[] {" "}, StringSplitOptions.None);
List< string> ret = new List<string>();
foreach (string split in splitted)
{
string vows = string.Empty;
string cons = string.Empty;
for (var i = 0; i < split.Length; i++)
{
char ch = split[i];
if (vow.Contains(ch))
{
vows += ch;
}
else
{
cons += ch;
}
}
ret.Add(cons + vows + "ay");
}
return ret.ToArray();
}
This is a (little bit hacky) solution. I tested it with the examples from Wiki.
public static string ToPigLatin(string word)
{
string result = string.Empty;
string pigSuffixVowelFirst = "yay";
string pigSuffixConstanantsFirst = "ay";
string vowels = "aeiouAEIOU";
if(vowels.Contains(word.First()))
{
result = word + pigSuffixVowelFirst;
}
else
{
int count = 0;
string end = string.Empty;
foreach(char c in word)
{
if (!vowels.Contains(c))
{
end += c;
count++;
}
else
{
break;
}
}
result = word.Substring(count) + end + pigSuffixConstanantsFirst;
}
return result;
}
Use at your own peril :)

Can't get my method to upper case my string arrays

The whole program is listed after, but the only problem i have with it is the ToUppers() method. I just want this method to iterate over each string in my array, and then make everything upper case.
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper(); // <== this line highlighted
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
The program executes after it prints it on the console, and it lists a NullReferenceException, and highlights the stringer = value.ToUpper(); line
The whole program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//Mark Bouwman
//CNT A01
//ICA18
//April 2nd
string answer;
int numInArray;
string[] stringArrays;
string[] stringArraysToDisplay;
string[] stringToUpperArrays;
//TITLE
Console.WriteLine("\t\tStringy");
do
{
numInArray = Utility.Utility.GetInt(2, 10, "Enter the size of the array from 2 to 10: ");
stringArrays = CreateArray(numInArray);
stringArraysToDisplay = Display(stringArrays);
stringToUpperArrays = ToUppers(stringArrays);
//aksing to run program again
Console.Write("Run program again? yes or no: ");
answer = Console.ReadLine();
}
while (answer.Equals("yes", StringComparison.CurrentCultureIgnoreCase));
}
private static string[] CreateArray(int numInArray)
{
int index;
string[] stringArray;
stringArray = new string[(numInArray + 1)];
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
return stringArray;
}
private static string[] Display(string[] stringArraysDisplay)
{
foreach (string value in stringArraysDisplay)
{
Console.WriteLine(value);
}
return stringArraysDisplay;
}
private static string[] ToUppers(string[] stringToUpperArrays)
{
string stringer;
foreach (string value in stringToUpperArrays)
{
stringer = value.ToUpper();
Console.WriteLine(stringer);
}
return stringToUpperArrays;
}
}
}
In CreateArray you define the array to size of numInArray + 1 but you fill the array only with numInArray strings, i.e. the last index is empty. When you try value.ToUpper(); on the empty index you get the exception.
In CreateArray change
stringArray = new string[(numInArray + 1)];
To
stringArray = new string[numInArray];
Or change
for (index = 0; index < numInArray; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
To
for (index = 0; index < stringArray.Length; ++index)
{
Console.Write("Enter string #" + (index + 1) + " ");
stringArray[index] = Console.ReadLine();
}
You should erase the + 1 when you are initializing the array
stringArray = new string[(numInArray)];
in this method
private static string[] CreateArray(int numInArray)

C# pass gen recursion

I have a password generator that uses the ascii table. I am trying to learn how to use the recursion with it. I know there are easy ways to make a generator but I want to learn more about recursion. I want it to choose the letters (65-90) but also choose the numbers (000 - 009)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class PasswordGenerator
{
static void Main()
{
bool bypass = false;
string errorMessage = "That is an Invalid Number, Please try again";
string howManyCharacters = "How many Characters would you like the Password to be? (Press '0' to Stop)";
string pressKeyMessage = "Press any key to continue";
int length = 0;
do
{
var passwordBuilder = new StringBuilder();
Console.WriteLine(howManyCharacters);
var inputIsNumber = int.TryParse(Console.ReadLine(), out length);
if (!inputIsNumber)
{
Console.WriteLine(errorMessage);
bypass = false;
}
else if (inputIsNumber && length != 0)
{
for (int i = 0; i < length; i++)
passwordBuilder.Append(GetRandomChar());
Console.WriteLine();
Console.WriteLine("Password: " + passwordBuilder.ToString());
Console.WriteLine();
}
else
{
Console.WriteLine();
Console.WriteLine(pressKeyMessage);
Console.ReadLine();
bypass = true;
}
}
while (!bypass);
}
static Random _r = new Random();
static char GetRandomChar()
{
return (char)_r.Next(65, 90); // A through Z
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class PasswordGenerator
{
static void Main()
{
bool bypass = false;
int length = 0;
do
{
var passwordBuilder = new StringBuilder();
Console.WriteLine("How many Characters would you like the Password to be? (Press '-1' to Stop)");
/// try method is inside, replaced old try and catch
var Input_is_Int = int.TryParse(Console.ReadLine(), out length);
if (!Input_is_Int || length == 0)
{
Console.WriteLine("That is an Invalid Number, Please try again");
Console.WriteLine();
bypass = false;
}
else if (Input_is_Int && length != -1)
{
for (int i = 0; i < length; i++)
passwordBuilder.Append(GetRandomChar());
Console.WriteLine("Password: " + passwordBuilder.ToString());
Console.WriteLine();
}
else
{
Console.WriteLine();
Console.WriteLine("Press any key to continue");
Console.ReadLine();
bypass = true;
}
}
while (!bypass);
}
/// Union of ABCDEFGHIJKLMNOPQRSTUVWXYZ, 0123456789 and !"#$%&'()*+,-./
static char[] _lookupTable = Enumerable.Range(65, 26).Union(Enumerable.Range(48, 10).Union(Enumerable.Range(33, 14))).Select(i => (char)i).ToArray();
static Random _r = new Random();
static char GetRandomChar()
{
var index = _r.Next(0, _lookupTable.Length);
return _lookupTable[index];
}
}

Categories

Resources