olidev
olidev

Reputation: 20644

Check if a string start with any character in a list

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?

Upvotes: 13

Views: 31975

Answers (14)

marianotigre
marianotigre

Reputation: 128

It is very usefull to use a string extension:

public static class StringExtensions
{
    public static bool StartsWithAny(this string stack, params string[] needles) {
        return needles.Any(stack.StartsWith);
    }
}

my full class is like this:

public static class StringExtensions
{
    public static bool StartsWithAny(this string stack, params string[] needles) {
        return needles.Any(stack.StartsWith);
    }

    public static bool ContainsAny(this string stack, params string[] needles) {
        return needles.Any(stack.Contains);
    }

    public static bool IsOneOf<T>(this T value, params T[] items) {
        for (int i = 0; i < items.Length; ++i) {
            if (items[i].Equals(value))
                return true;
        }
        return false;
    }
}

Upvotes: 0

Stefan Michev
Stefan Michev

Reputation: 5093

In such cases I use an extension method like this:

public static bool StartsWithAny(this string Text, IEnumerable<string> Needles) {
            return Needles.Any(x => Text.StartsWith(x));
        }

Upvotes: 0

djskinner
djskinner

Reputation: 8125

I needed something similar, but for strings:

I wanted to know if my string subject started with any of these strings:

var qualent3s = new string[] { "D", "M", "H", "JUK"};

The LINQ to do so is simple:

qualent3s.Any(x => subject.StartsWith(x))

Upvotes: 8

Chen Kinnrot
Chen Kinnrot

Reputation: 21015

return columnChars.Any(x => x == toCheck[0]);

Upvotes: 3

SRM
SRM

Reputation: 1377

I love my linq so here:

        string str = "A quick brown fox";
        char[] chars = { 'A', 'B', 'C', 'D', 'E', 'F' };

        var query = from c in str.Substring(0, 1)
                    join c1 in chars on c equals c1
                    select c;

That will give you all the characters, in the list, that match the first character of the string. A little modification and you could even get the index of the character in the list of characters you are searching, in this case index 0.

here is that code:

        string str = "A quick brown fox";
        char[] chars = { 'Z', 'X', 'A', 'B', 'C', 'D', 'E', 'F' };

        var query = from c in str.Substring(0, 1)
                    join c1 in chars on c equals c1
                    select new { Character = c, Index = chars.ToList().IndexOf(c) };

        var found = query.ToArray();

Upvotes: 0

Dan Tao
Dan Tao

Reputation: 128327

If your character "list" is definitely going to be a char[], I would assume you're best off with:

return toCheck.IndexOfAny(columnChars) == 0;

Disclaimer: I haven't benchmarked this. But that method's just sitting there.

Upvotes: 3

Chandu
Chandu

Reputation: 82913

You can do it using Contains and ElementAt:

char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' }; 
String testString = "This is test String";
var exists = columnChars.Contains(testString.ElementAt(0));

Upvotes: 0

JYelton
JYelton

Reputation: 36512

Here is what I came up with:

    readonly char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };
    private bool startWithColumn(string toCheck)
    {
        return columnChars.Contains(toCheck.Substring(0, 1).ToCharArray()[0]);
    }

Edit

Didn't see a possibility for making fewer conversions:

    readonly char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };
    private bool startWithColumn(string toCheck)
    {
        return columnChars.Contains(toCheck[0]);
    }

Upvotes: 0

Ani
Ani

Reputation: 113442

The obvious way would be to linear-search the array for the first character of the string:

private bool startWithColumn(string toCheck)
{
     return !string.IsNullOrEmpty(toCheck) 
           && Array.IndexOf(columnChars, toCheck[0]) != -1; 
}

If you're looking for performance, consider using a HashSet<char> or similar instead of an array, which should give you a constant-time lookup. This is probably only worth it if the array were much larger; you'll have to measure one way or another.

Upvotes: 0

Artemiy
Artemiy

Reputation: 1979

private bool startWithColumn(string toCheck)
{
  return (columnChars.IndexOf(toCheck[0]) >=0);
}

Upvotes: 0

Lee
Lee

Reputation: 144136

return Regex.IsMatch(toCheck, "^[A-E]");

Alternatively:

return toCheck.Length > 0 && columnChars.Contains(toCheck[0]);

Upvotes: 2

tvanfosson
tvanfosson

Reputation: 532505

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] );
 }

Upvotes: 11

Victor Haydin
Victor Haydin

Reputation: 3548

I believe this one would be faster:

char[] columnChars = new char[] { 'A', 'B', 'C', 'D', 'E' };
private bool startWithColumn(string toCheck)
{
   for(int i=0; i<columnChars.Length; i++)   
     if (toCheck.Length > 0 && toCheck[0] == columnChars[i]))
     {
       return true;
     }

   return false;
}

Upvotes: 0

Anon.
Anon.

Reputation: 59993

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);

Upvotes: 8

Related Questions