Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
string
startswith()
communitycreator

How to check whether a string starts with a certain string in C#

Theodore Kelechukwu Onyejiaku

When you want to check if a string starts with a particular substring or string, then look no further. The C# StartsWith() method provides the solution.

Syntax

str.StartsWith(match)

Parameters

  • str: This is the string to check.
  • match: This is the character or string to check at the beginning of str.

Return value

The value returned is a boolean. It is true if match matches the beginning of str. Otherwise, false is returned.

Code example

// create class
class StringChecker
{
    // create main method
    static void Main()
    {
      // create strings
      string s1 = "Welcome";
      string s2 = "to";
      string s3 = "Edpresso";

      // check strings above\
      bool check1 = s1.StartsWith("W");    // true
      bool check2 = s2.StartsWith("y");    // false
      bool check3 = s3.StartsWith("Edp");  // true

      // print out reuturned values
      System.Console.WriteLine(check1);
      System.Console.WriteLine(check2);
      System.Console.WriteLine(check3);
    }
}

RELATED TAGS

c#
string
startswith()
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring