Let's say I have an array of strings:
string[] greeting = new string[] {"hey", "hello", "hi"};
if the user input is any of the following words: "hey" "hello" "hi" then I want the console to print "hey there". This is what I did:
string userInput = Console.ReadLine();
bool result_a = userInput.StartsWith(greeting);
if(result_a) { Console.WriteLine("hey there"); }
but that doesn't seem to be working.
CodePudding user response:
If what you want is, whenever the user starts with any of the 3
using System;
using System.Linq;
...
string[] greeting = new string[] {"hey", "hello", "hi"};
string userInput = Console.ReadLine();
bool result_a = greeting.Any(a => userInput.Trim().StartsWith(a));
if(result_a) { Console.WriteLine("hey there"); }
Example: "hi my name is Ali"
Now if you want capital letters to work as well you need to change the line to:
Example: "Hi my name is Ali"
bool result_a = greeting.Any(a => userInput.Trim().ToLower().StartsWith(a));
If what you want is, whenever the user input contains then:
using System;
using System.Linq;
...
string[] greeting = new string[] {"hey", "hello", "hi"};
string userInput = Console.ReadLine();
bool result_a = greeting.Any(a => userInput.Trim().Contains(a));
if(result_a) { Console.WriteLine("hey there"); }
Example: "Good morning! hello"
Now if you want capital letters to work as well you need to change the line to:
Example: "Good morning! Hello"
bool result_a = greeting.Any(a => userInput.Trim().ToLower().Contains(a));
CodePudding user response:
string[] greeting = new string[] { "hey", "hello", "hi" };
string userInput = Console.ReadLine();
bool result_a = greeting.Any(x=>x.StartsWith(userInput));
if (result_a) { Console.WriteLine("hey there"); }
if (result_a) { Console.WriteLine($"{greeting.FirstOrDefault(x => x.StartsWith(userInput))} there"); }
CodePudding user response:
try this,bro
List<string> greeting = new List<string>();
greeting.Add("hey");
greeting.Add("hello");
greeting.Add("hi");
string userInput = Console.ReadLine();
if (greeting.Contains(userInput.Trim()))
{
Console.WriteLine("hey there");
}