C# `StartsWith()` Method: Efficient String Beginning Checks

Learn how to efficiently check if a string starts with a specific substring in C# using the `StartsWith()` method. This tutorial explores different overloads, including case-sensitive and case-insensitive comparisons, providing practical examples for string validation and manipulation.



Checking String Beginnings in C# with `StartsWith()`

Understanding `String.StartsWith()`

The C# `StartsWith()` method checks if a string begins with a specified substring. This is a useful method for validating strings, performing string comparisons, or for extracting specific portions of strings. The comparison is case-sensitive by default, but you can modify this behavior using different overloads of the `StartsWith()` method.

`String.StartsWith()` Method Signatures

The `StartsWith()` method has several overloads to handle different comparison scenarios:

  • public bool StartsWith(string value);: Checks if the string starts with the specified value (case-sensitive).
  • public bool StartsWith(string value, StringComparison comparisonType);: Allows you to specify the comparison type (case-sensitive or insensitive, etc.).
  • public bool StartsWith(string value, bool ignoreCase, CultureInfo culture);: Provides more fine-grained control for culture-specific case-insensitive comparisons.

Example: Checking String Beginnings

This example checks if the string "Hello C#" starts with "h" (lowercase) and "H" (uppercase). Because the `StartsWith()` method is case-sensitive by default, the first check returns `false`, and the second returns `true`.

C# Code

using System;

public class StartsWithExample {
    public static void Main(string[] args) {
        string myString = "Hello C#";
        Console.WriteLine(myString.StartsWith("h")); // False (case-sensitive)
        Console.WriteLine(myString.StartsWith("H")); // True  (case-sensitive)
    }
}

Conclusion

The `StartsWith()` method is a valuable tool for string manipulation in C#. Its various overloads offer great flexibility in checking whether a string begins with a specific substring, enabling you to write cleaner and more effective code for string validation and processing.