Related
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)];
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
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 :)
I have a program, in which you can input a string. But I want text between quotes " " to be removed.
Example:
in: Today is a very "nice" and hot day.
out: Today is a very "" and hot day.
Console.WriteLine("Enter text: ");
text = Console.ReadLine();
int letter;
string s = null;
string s2 = null;
for (s = 0; s < text.Length; letter++)
{
if (text[letter] != '"')
{
s = s + text[letter];
}
else if (text[letter] == '"')
{
s2 = s2 + letter;
letter++;
(text[letter] != '"')
{
s2 = s2 + letter;
letter++;
}
}
}
I don't know how to write the string without text between quotes to the console.
I am not allowed to use a complex method like regex.
This should do the trick. It checks every character in the string for quotes.
If it finds quotes then sets a quotesOpened flag as true, so it will ignore any subsequent character.
When it encounters another quotes, it sets the flag to false, so it will resume copying the characters.
Console.WriteLine("Enter text: ");
text = Console.ReadLine();
int letterIndex;
string s2 = "";
bool quotesOpened = false;
for (letterIndex= 0; letterIndex< text.Length; letterIndex++)
{
if (text[letterIndex] == '"')
{
quotesOpened = !quotesOpened;
s2 = s2 + text[letterIndex];
}
else
{
if (!quotesOpened)
s2 = s2 + text[letterIndex];
}
}
Hope this helps!
A take without regular expressions, which I like better, but okay:
string input = "abc\"def\"ghi";
string output = input;
int firstQuoteIndex = input.IndexOf("\"");
if (firstQuoteIndex >= 0)
{
int secondQuoteIndex = input.IndexOf("\"", firstQuoteIndex + 1);
if (secondQuoteIndex >= 0)
{
output = input.Substring(0, firstQuoteIndex + 1) + input.Substring(secondQuoteIndex);
}
}
Console.WriteLine(output);
What it does:
It searches for the first occurrence of "
Then it searches for the second occurrence of "
Then it takes the first part, including the first " and the second part, including the second "
You could improve this yourself by searching until the end of the string and replace all occurrences. You have to remember the new 'first index' you have to search on.
string text = #" Today is a very ""nice"" and hot day. Second sentense with ""text"" test";
Regex r = new Regex("\"([^\"]*)\"");
var a = r.Replace(text,string.Empty);
Please try this.
First we need to split string and then remove odd items:
private static String Remove(String s)
{
var rs = s.Split(new[] { '"' }).ToList();
return String.Join("\"\"", rs.Where(_ => rs.IndexOf(_) % 2 == 0));
}
static void Main(string[] args)
{
var test = Remove("hello\"world\"\"yeah\" test \"fhfh\"");
return;
}
This would be a possible solution:
String cmd = "This is a \"Test\".";
// This is a "".
String newCmd = cmd.Split('\"')[0] + "\"\"" + cmd.Split('\"')[2];
Console.WriteLine(newCmd);
Console.Read();
You simply split the text at " and then add both parts together and add the old ". Not a very nice solution, but it works anyway.
€dit:
cmd[0] = "This is a "
cmd[1] = "Test"
cmd[2] = "."
You can do it like this:
Console.WriteLine("Enter text: ");
var text = Console.ReadLine();
var skipping = false;
var result = string.Empty;
foreach (var c in text)
{
if (!skipping || c == '"') result += c;
if (c == '"') skipping = !skipping;
}
Console.WriteLine(result);
Console.ReadLine();
The result string is created by adding characters from the original string as long we are not between quotes (using the skipping variable).
Take all indexes of quotes remove the text between quotes using substring.
static void Main(string[] args)
{
string text = #" Today is a very ""nice"" and hot day. Second sentense with ""text"" test";
var foundIndexes = new List<int>();
foundIndexes.Add(0);
for (int i = 0; i < text.Length; i++)
{
if (text[i] == '"')
foundIndexes.Add(i);
}
string result = "";
for(int i =0; i<foundIndexes.Count; i+=2)
{
int length = 0;
if(i == foundIndexes.Count - 1)
{
length = text.Length - foundIndexes[i];
}
else
{
length = foundIndexes[i + 1] - foundIndexes[i]+1;
}
result += text.Substring(foundIndexes[i], length);
}
Console.WriteLine(result);
Console.ReadKey();
}
Output: Today is a very "" and hot day. Second sentense with "" test";
Here dotNetFiddle
How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:
This is an example string and my data is here
And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.
Use this method:
public static string getBetween(string strSource, string strStart, string strEnd)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
int Start, End;
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
return strSource.Substring(Start, End - Start);
}
return "";
}
How to use it:
string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");
This is the simplest way:
if(str.Contains("hello"))
You could use Regex:
var regex = new Regex(".*my (.*) is.*");
if (regex.IsMatch("This is an example string and my data is here"))
{
var myCapturedText = regex.Match("This is an example string and my data is here").Groups[1].Value;
Console.WriteLine("This is my captured text: {0}", myCapturedText);
}
string string1 = "This is an example string and my data is here";
string toFind1 = "my";
string toFind2 = "is";
int start = string1.IndexOf(toFind1) + toFind1.Length;
int end = string1.IndexOf(toFind2, start); //Start after the index of 'my' since 'is' appears twice
string string2 = string1.Substring(start, end - start);
Here's my function using Oscar Jara's function as a model.
public static string getBetween(string strSource, string strStart, string strEnd) {
const int kNotFound = -1;
var startIdx = strSource.IndexOf(strStart);
if (startIdx != kNotFound) {
startIdx += strStart.Length;
var endIdx = strSource.IndexOf(strEnd, startIdx);
if (endIdx > startIdx) {
return strSource.Substring(startIdx, endIdx - startIdx);
}
}
return String.Empty;
}
This version does at most two searches of the text. It avoids an exception thrown by Oscar's version when searching for an end string that only occurs before the start string, i.e., getBetween(text, "my", "and");.
Usage is the same:
string text = "This is an example string and my data is here";
string data = getBetween(text, "my", "is");
You can do it compactly like this:
string abc = abc.Replace(abc.Substring(abc.IndexOf("me"), (abc.IndexOf("is", abc.IndexOf("me")) + 1) - abc.IndexOf("size")), string.Empty);
Except for #Prashant's answer, the above answers have been answered incorrectly. Where is the "replace" feature of the answer? The OP asked, "After that, I'd like to create a new string between that and something else".
Based on #Oscar's excellent response, I have expanded his function to be a "Search And Replace" function in one.
I think #Prashant's answer should have been the accepted answer by the OP, as it does a replace.
Anyway, I've called my variant - ReplaceBetween().
public static string ReplaceBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
string strToReplace = strSource.Substring(Start, End - Start);
string newString = strSource.Concat(Start,strReplace,End - Start);
return newString;
}
else
{
return string.Empty;
}
}
static void Main(string[] args)
{
int f = 0;
Console.WriteLine("enter the string");
string s = Console.ReadLine();
Console.WriteLine("enter the word to be searched");
string a = Console.ReadLine();
int l = s.Length;
int c = a.Length;
for (int i = 0; i < l; i++)
{
if (s[i] == a[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (s[K] == a[j])
{
f++;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
string WordInBetween(string sentence, string wordOne, string wordTwo)
{
int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;
int end = sentence.IndexOf(wordTwo) - start - 1;
return sentence.Substring(start, end);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Diagnostics;
namespace oops3
{
public class Demo
{
static void Main(string[] args)
{
Console.WriteLine("Enter the string");
string x = Console.ReadLine();
Console.WriteLine("enter the string to be searched");
string SearchText = Console.ReadLine();
string[] myarr = new string[30];
myarr = x.Split(' ');
int i = 0;
foreach(string s in myarr)
{
i = i + 1;
if (s==SearchText)
{
Console.WriteLine("The string found at position:" + i);
}
}
Console.ReadLine();
}
}
}
This is the correct way to replace a portion of text inside a string (based upon the getBetween method by Oscar Jara):
public static string ReplaceTextBetween(string strSource, string strStart, string strEnd, string strReplace)
{
int Start, End, strSourceEnd;
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
Start = strSource.IndexOf(strStart, 0) + strStart.Length;
End = strSource.IndexOf(strEnd, Start);
strSourceEnd = strSource.Length - 1;
string strToReplace = strSource.Substring(Start, End - Start);
string newString = string.Concat(strSource.Substring(0, Start), strReplace, strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start));
return newString;
}
else
{
return string.Empty;
}
}
The string.Concat concatenates 3 strings:
The string source portion before the string to replace found - strSource.Substring(0, Start)
The replacing string - strReplace
The string source portion after the string to replace found - strSource.Substring(Start + strToReplace.Length, strSourceEnd - Start)
Simply add this code:
if (string.Contains("search_text")) {
MessageBox.Show("Message.");
}
If you know that you always want the string between "my" and "is", then you can always perform the following:
string message = "This is an example string and my data is here";
//Get the string position of the first word and add two (for it's length)
int pos1 = message.IndexOf("my") + 2;
//Get the string position of the next word, starting index being after the first position
int pos2 = message.IndexOf("is", pos1);
//use substring to obtain the information in between and store in a new string
string data = message.Substring(pos1, pos2 - pos1).Trim();
First find the index of text and then substring
var ind = Directory.GetCurrentDirectory().ToString().IndexOf("TEXT To find");
string productFolder = Directory.GetCurrentDirectory().ToString().Substring(0, ind);
I have different approach on ReplaceTextBetween() function.
public static string ReplaceTextBetween(this string strSource, string strStart, string strEnd, string strReplace)
{
if (strSource.Contains(strStart) && strSource.Contains(strEnd))
{
var startIndex = strSource.IndexOf(strStart, 0) + strStart.Length;
var endIndex = strSource.IndexOf(strEnd, startIndex);
var strSourceLength = strSource.Length;
var strToReplace = strSource.Substring(startIndex, endIndex - startIndex);
var concatStart = startIndex + strToReplace.Length;
var beforeReplaceStr = strSource.Substring(0, startIndex);
var afterReplaceStr = strSource.Substring(concatStart, strSourceLength - endIndex);
return string.Concat(beforeReplaceStr, strReplace, afterReplaceStr);
}
return strSource;
}
Correct answer here without using any pre-defined method.
static void WordContainsInString()
{
int f = 0;
Console.WriteLine("Input the string");
string str = Console.ReadLine();
Console.WriteLine("Input the word to search");
string word = Console.ReadLine();
int l = str.Length;
int c = word.Length;
for (int i = 0; i < l; i++)
{
if (str[i] == word[0])
{
for (int K = i + 1, j = 1; j < c; j++, K++)
{
if (str[K] == word[j])
{
f++;
}
else
{
f = 0;
}
}
}
}
if (f == c - 1)
{
Console.WriteLine("matching");
}
else
{
Console.WriteLine("not found");
}
Console.ReadLine();
}
for .net 6 can use next code
public static string? Crop(string? text, string? start, string? end = default)
{
if (text == null) return null;
string? result;
var startIndex = string.IsNullOrEmpty(start) ? 0 : text.IndexOf(start);
if (startIndex < 0) return null;
startIndex += start?.Length ?? 0;
if (string.IsNullOrEmpty(end))
{
result = text.Substring(startIndex);
}
else
{
var endIndex = text.IndexOf(end, startIndex);
if (endIndex < 0) return null;
result = text.Substring(startIndex, endIndex - startIndex);
}
return result;
}