I want to check whether a string starts with any character in a list. My current implementation in C# is as follows:
char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };
private bool startWithColumn(string toCheck)
{
for(int i=0; i<columnChars.Length; i++)
if (toCheck.StartsWith(columnChars[i]+""))
{
return true;
}
return false;
}
I would like to know if any solution is better?
The startsWith() method returns true if a string starts with a specified string. Otherwise it returns false . The startsWith() method is case sensitive. See also the endsWith() method.
Check if a string starts with any element in the list in Python. Python example code use str. startswith() to find it a string starts with some string in a list. In the example list of substrings has converted into a tuple using tuple(list) in order to return a boolean if str contains substrings found it.
Using String. contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.
Python String startswith() The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .
Turn the check around and see if the first character is in the allowable set.
char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };
private bool startWithColumn(string toCheck)
{
return toCheck != null
&& toCheck.Length > 0
&& columnChars.Any( c => c == toCheck[0] );
}
You can get the first character out of a string easily enough:
char c = toCheck[0];
And then check whether it's in the array:
return columnChars.Contains(c);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With