C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ContainsChars: This returns a boolean value. This indicates whether the constant string was found in a case-insensitive way in the source string.
Bool MethodSwitch CharHere: We search for the four characters "gzip" in that order in a case-insensitive way. We use four nested switch statements in a loop.
Note: We treat the current character based on the induction variable loop index. We then check the next three characters.
Main: This provides a basic correctness check that shows that the method works. Having a correct method is important.
C# program that uses nested switch statements
using System;
class Program
{
static bool ContainsChars(string value)
{
//
// Uses three nested switch statements in a loop to scan character patterns.
//
for (int i = 0; i < value.Length - 3; i++)
{
switch (value[i])
{
case 'g':
case 'G':
switch (value[i + 1])
{
case 'z':
case 'Z':
switch (value[i + 2])
{
case 'i':
case 'I':
switch (value[i + 3])
{
case 'p':
case 'P':
return true;
}
break;
}
break;
}
break;
}
}
return false;
}
static void Main()
{
//
// Test the output of the nested switch method.
//
Console.WriteLine(ContainsChars("GZip"));
Console.WriteLine(ContainsChars("deflate, gzip"));
Console.WriteLine(ContainsChars("zgip"));
Console.WriteLine(ContainsChars("Gzi"));
}
}
Output
True
True
False
False
Also: A method that uses if-statements instead of the nested switch statements is about 0.3 nanoseconds slower per call.
Boyer-Moore: Another option is the Boyer-Moore string search. This skips ahead once an invalid character is found.