Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string start with any character in a list

Tags:

c#

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?

like image 355
olidev Avatar asked Jan 12 '11 22:01

olidev


People also ask

How do you check if a string starts with a certain character?

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.

How do you check if a string starts with something in a list Python?

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.

How do you check if a string contains a string from a list?

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.

How do you check if a string starts with a particular word in Python?

Python String startswith() The startswith() method returns True if a string starts with the specified prefix(string). If not, it returns False .


2 Answers

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] );
 }
like image 67
tvanfosson Avatar answered Sep 22 '22 03:09

tvanfosson


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);
like image 33
Anon. Avatar answered Sep 18 '22 03:09

Anon.