IAmConfused
IAmConfused

Reputation: 123

Get index of next non-whitespace character in string

Given the following string as an example:

"ABC  DEF    GHI"
How can I find the index of the next non-whitespace character if I wanted to start my search from index 8 (the first space after the F)?

Is there a "neat" way I can achieve this without reverting to a simple for loop comparing with Char.IsWhitespace(), or taking a substring and using a solution from Get Index of First non-Whitespace Character in C# String

(btw when I say "neat" above I'm not keen on getting into a discussion as to why I may or may not think the solutions I've mentioned are "neat" - just interested in learning something new thanks!)

Upvotes: 0

Views: 4255

Answers (3)

w.b
w.b

Reputation: 11228

This uses LINQ only:

string str = "ABC  DEF    GHI";

int result = str.Select((c, index) => { if (index > 8 && !Char.IsWhiteSpace(c)) return index; return -1; })
                .FirstOrDefault(i => i != -1);

Console.WriteLine(result == default(int) ?  "Index not found" : result.ToString());   // 12

Upvotes: 0

Ivan Stoev
Ivan Stoev

Reputation: 205589

Is there a "neat" way I can achieve this

Here it is:

void Foo(string s)
{
    int index = s.IndexOfNonWhitespace(8);
}

Not compiling? Well, you asked for a "neat" way and I just showed it. There is no such "standard" way provided by the BCL, but that's why the programmers and extension methods exist.

So, in some common place you will write once something like this and then use it anytime and anywhere you want:

public static class MyExtensions
{
    public static int IndexOfNonWhitespace(this string source, int startIndex = 0)
    {
        if (startIndex < 0) throw new ArgumentOutOfRangeException("startIndex");
        if (source != null)
            for (int i = startIndex; i < source.Length; i++)
                if (!char.IsWhiteSpace(source[i])) return i;
        return -1;
    }
}

If you say the implementation is not "neat", it does not need to be - take a look at the http://referencesource.microsoft.com/

Upvotes: 2

Tao G&#243;mez Gil
Tao G&#243;mez Gil

Reputation: 2695

If the index you want to start from is 8, you can use this:

string text = "ABC  DEF    GHI";
int index = text.IndexOf(text.Skip(8).First(c => !char.IsWhiteSpace(c)));

Basically, you skip the first 8 characters, take the first that it's not white space and get its index. It's not the most efficient way, thought, but it's really readable.

If the starting index is not fixed, you will have to find that index first and inject it into the expression.

Upvotes: 2

Related Questions