C# String StartsWith()

The String StartsWith() method checks whether the string starts with the specified string or not.

Example

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      bool result;
     
// checks if "Icecream" starts with "Ice" result = str.StartsWith("Ice");
Console.WriteLine(result); Console.ReadLine(); } } } // Output: True

StartsWith() Syntax

The syntax of the string StartsWith() method is:

StartsWith(String value, StringComparison comparisonType)

Here, StartsWith() is a method of class String.


StartsWith() Parameters

The StartsWith() method takes the following parameters:

  • value - string to compare
  • comparisonType - determines how the given string and value are compared.

StartsWith() Return Value

The StartsWith() method returns:

  • True - if the string begins with the value
  • False - if the string does not begin with the value

Example 1: C# String StartsWith()

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      bool result;

// checks if "Icecream" starts with "I" result = str.StartsWith("I");
Console.WriteLine("Starts with I: " + result);
// checks if "Icecream" starts with "i" result = str.StartsWith("i");
Console.WriteLine("Starts with i: " + result); Console.ReadLine(); } } }

Output

Starts with I: True
Starts with i: False

Example 2: C# String StartsWith() With comparisonType

using System;  
namespace CsharpString {  
  class Test {
    public static void Main(string [] args) {
     
      string str = "Icecream";
      bool result;
     
// considers letter case result = str.StartsWith("ice", StringComparison.InvariantCulture);
Console.WriteLine("Starts with ice: " + result);
// ignores letter case result = str.StartsWith("ice", StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine("Starts with ice: " + result); Console.ReadLine(); } } }

Output

Starts with ice: False
Starts with ice: True

Here,

  • StringComparison.InvariantCulture - considers letter case
  • StringComparison.InvariantCultureIgnoreCase - ignores letter case
Did you find this article helpful?