Arion
Arion

Reputation: 31249

Count startswith with linq

So I have a question regarding how to count the starts with of a string in linq. Let me explain with some test cases

Test case #1

var target="test";
var source="test2";

The output should be 4

Test case #2

var target="te";
var source="test2";

The output should be 2

Test case #3:

var target="tet";
var source="test2";

The output should be 0. Because the source do not starts with target

So I came up with this function:

private int CountStartsWith(string source, string target)
{
  if (!source.StartsWith(target))
      return 0;

  return source.ToCharArray()
      .Zip(target.ToCharArray(), (s1, s2) => (s1 == s2))
      .TakeWhile(match => match)
      .Count();
}

It works for the test cases that I have. But my question is can this be done in an easier way?

Upvotes: 3

Views: 468

Answers (2)

Marcel B
Marcel B

Reputation: 3674

if (!source.StartsWith(target)) return 0;
return target.Length;

Upvotes: 7

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

You may try

return source.StartsWith(target, StringComparison.OrdinalIgnoreCase) ? target.Length : 0;

Upvotes: 4

Related Questions