C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
We use it to test the first characters in a string against another string. It is possible to test many strings with the foreach-loop and match common strings such as URLs.
Example. We first test URL strings, a common task 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 that the input string matches a URL we can accept.
So: 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"; // 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
Example 2. Next, we see that foreach can be used with StartsWith. 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.
C# program that uses StartsWith in loop body using System; class Program { static void Main() { // The input string. string input = "http://site.com/test"; // 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
Summary. We used the StartsWith instance method in several different ways to test strings such as URLs. StartsWith tests the first characters of strings. It returns a bool telling us whether or not the starts match.
Further: We used if-statements, and foreach with if-statements, alongside the StartsWith method on the string type.