c# - Checking if a string begins with a given string -


i new programming. need determine if given string begins something. example check if string begins "hi" return true, return false if it's "high".

starthi("hi there") -> true; starthi("hi") -> true; starthi("high five") -> false. 

i've tried .substring , .startswith, can't figure out how make them return false "high five". i've tried this:

public static bool starthi(string str) {     bool firsthi;     if(string.isnullorempty(str))     {         console.writeline("the string empty!");     }     else if(str.substring(0,2) == "hi")     {         firsthi = true;         console.writeline("the string starts \"hi\"");     }     else     {         firsthi = false;         console.writeline("the string doesn't start \"hi\"");     }     console.readline();      return firsthi; 

} .startswith, changed "else if":

else if(str.startswith("hi")) {     firsthi = true;     console.writeline("the string starts \"hi\""); } 

thank in advance!

write starthi method below using split

    public static bool starthi(string str)     {         bool firsthi = false;         if (string.isnullorempty(str))         {             console.writeline("the string empty!");             console.readline();             return false;         }          var array = str.split(new string[] {" "}, stringsplitoptions.none);         if (array[0].tolower() == "hi")         {             firsthi = true;             console.writeline("the string starts \"hi\"");         }         else         {             firsthi = false;             console.writeline("the string doesn't start \"hi\"");         }          console.readline();          return firsthi;     } 

note: if have other strings "hi!" or "hi? don't hi me", can extend split below.

var array = str.split(new string[] {" ", "!", "?"}, stringsplitoptions.none); if (array[0].tolower() == "hi") //convert lower , check 

regex best bet if gets more complicated , towards it. can't give 1 since i'm not great it.


Comments

Popular posts from this blog

javascript - Karma not able to start PhantomJS on Windows - Error: spawn UNKNOWN -

Nuget pack csproj using nuspec -

c# - Display ASPX Popup control in RowDeleteing Event (ASPX Gridview) -