
StartsWith tests the first part of strings. You can use the StartsWith instance method to test the first characters in a string against another string in your C# program. It is possible to test many strings with the foreach loop and match common strings such as URLs.
These C# examples show how to use the StartsWith method on strings.

Here we look at testing URL strings, which is common in web applications. In this case, we need to test the "http://www.site.com" string and the "http://site.com" string. The two statements in the if test that the input string matches a URL we can accept. In this way, you can use StartsWith for efficient testing of URLs.
Program that invokes StartsWith method [C#]
using System;
class Program
{
static void Main()
{
// The input string.
string input = "http://site.com/test.html";
// See if input matches one of these starts.
if (input.StartsWith("http://www.site.com") ||
input.StartsWith("http://site.com"))
{
// Write to the screen.
Console.WriteLine(true);
}
}
}
Output
TrueNext, we see that foreach can be used with StartsWith for an elegant and fairly efficient style of code. This example does the same thing as the first. It tests the URLs in the string array against the input string, returning true if there is a match.
Program that uses StartsWith in loop body [C#]
using System;
class Program
{
static void Main()
{
// The input string.
string input = "http://site.com/test.html";
// The possible matches.
string[] m = new string[]
{
"http://www.site.com",
"http://site.com"
};
// Loop through each possible match.
foreach (string s in m)
{
if (input.StartsWith(s))
{
// Will match second possibility.
Console.WriteLine(s);
return;
}
}
}
}
Output
http://site.com
In this example set, we saw how to use the StartsWith instance method in several different ways to test strings such as URLs. We used if statements and the foreach with if-statements to demonstrate the usefulness of the StartsWith instance method on the string type.
EndsWith Method String Type