Two ways come to mind to achieve this. The first would be to split the string on whitespace, into an array, then check the first entry of the array for "hi":
string[] words = str.split(' '); if ((words.length == 0 && str == "hi") || (words[0] == "hi")) return true; else return false;
The second would be to utilise the Regex and check if it matches "hi" at the start of the string:
return (System.Text.RegularExpressions.Regex.Match(str, @"^hi\b").Success);
Both of these will only find "hi" however (case specific). If you wish to check for "hi", "Hi", "HI" or "Hi", then you would likely want to use the ".ToLower()" method on the string object:
string lowerStr = str.ToLower(); string[] words = lowerStr.split(' '); if ((words.length == 0 && lowerStr == "hi") || (words[0] == "hi")) return true; else return false;
An example of your StartHi method may look like this:
public static bool StartHi(string str) { bool firstHi; if(string.IsNullOrEmpty(str)) { Console.WriteLine("The string is empty!"); } else { string strLower = str.ToLower(); string[] words = strLower.split(' '); if ((words.length == 0 && strLower == "hi") || (words[0] == "hi")) { firstHi = true; Console.WriteLine("The string starts with \"hi\""); } else { firstHi = false; Console.WriteLine("The string doesn't start with \"hi\""); } } Console.ReadLine(); return firstHi; }
If you needed to expand your criteria, and treat examples like "Hi!" and "Hi?" as a success, you should lean towards the Regex method. In which case, your method may look like the following:
public static bool StartHi(string str) { bool firstHi; if(string.IsNullOrEmpty(str)) { Console.WriteLine("The string is empty!"); } else if (System.Text.RegularExpressions.Regex.Match(str, @"^hi\b").Success)) { firstHi = true; Console.WriteLine("The string starts with \"hi\""); } else { firstHi = false; Console.WriteLine("The string doesn't start with \"hi\""); } Console.ReadLine(); return firstHi; }
@"^hi\b"str.StartsWith("hi ")?