C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: In this way, you can use StartsWith for efficient testing of URLs or other strings that have known starts.
C# program that invokes StartsWith method
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
True
C# program that uses StartsWith in loop
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
First: The EndsWith method, like its counterpart the StartsWith method, has three overloaded method signatures.
Here: The first example shows the simplest and first overload, which receives one parameter.
Tip: To use EndsWith, you must pass the string you want to check the ending with as the argument.
Next: An input string is tested for three ends. We detect the ending extension of the URL.
C# program that uses EndsWith
using System;
class Program
{
static void Main()
{
// The input string.
string input = "http://site.com";
// Test these endings.
string[] arr = new string[]
{
".net",
".com",
".org"
};
// Loop through and test each string.
foreach (string s in arr)
{
if (input.EndsWith(s))
{
Console.WriteLine(s);
return;
}
}
}
}
Output
.com
Tip: You can use StringComparison to specify case-insensitive matching with EndsWith—try OrdinalIgnoreCase.
StringComparison, StringComparerFinally: The third overload allows more globalization options, which are essential if non-English data will be encountered.