How to find the index of the first char in a string that is not in the list

I know I can iterate over a string or build a regex or invert the set (ASCII isn't that big) and look for the first instance of that, but Yuck.

What I'm looking for is a good liner.

fewer functions are better, LINQ is missing (for me don't ask, it's a long story)


Solution i am going with (unless i see anything better)

static int FirstNotMeta(int i, string str)
{
    for(; i < str.Length; i++)
        switch(str[i])
        {
            case '\\':
            case '/':
            case '.':
                continue;
            default:
                return i;
        }
    return -1;
}

      

OK, I cheated, I know in advance what char is about.

+1


source to share


4 answers


It works:



public static char FindFirstNotAny(this string value, params char[] charset)
{
    return value.TrimStart(charset)[0];
}

      

+7


source


If you don't have access to LINQ, I think you just need to write a static method with a loop (which is probably more efficient than LINQ). Remember that the compiler will create small methods someday.

The simplest non-LINQ I can think of is below. I recommend adding curly braces to keep the scope transparent:

public static char? GetFirstChar(string str, char[] list)
{
    foreach (char c in str) if (!list.Contains(c)) return c;
    return null;
}

      

With C # 3.0 and LINQ:

char[] list = { 'A', 'B' };
string str = "AABAGAF";

char first = str.ToArray().Where(c => !list.Contains(c)).FirstOrDefault();

      



In this case, if there is no character without a list, it will first be 0x0000 (or null character). You can do it:

char? first = str.ToArray().Cast<char?>().Where(
    c => !list.Contains(c.Value)).FirstOrDefault();

      

Then it will be null first if there is no match. It can also be written as:

var query = from char c in str
            where !list.Contains(c)
            select (char?)c;
char? first = query.FirstOrDefault();

      

+2


source


Not everything that is effective, but:

char f(string str, IEnumerable<char> list)
{
  return str.ToCharArray().First(c => !list.Contains(c))
}

      

+1


source


Will this C / C ++ example work for you:

char *strToSearch = "This is the one liner you want"
char *skipChars = "Tthise";
size_f numToSkip = strcspn(strToSearch, skipChars);

      

The function strcspn()

scans a string for complement to the specified set. It returns the number of leading characters that do not include a character in the set.

+1


source







All Articles