0

I want to count, how often I have \r\r in a string variable.

For example:

string sampleString = "9zogl22n\r\r\nv4bv79gy\r\r\nkaz73ji8\r\r\nxw0w91qq\r\r\ns05jxqxx\r\r\nw08qsxh0\r\r\nuyggbaec\r\r\nu2izr6y6\r\r\n106iha5t\r";

The result would be in this example 8.

123 456 789 0
  • 10,565
  • 4
  • 43
  • 72

5 Answers5

6

You can use a regular expression:

var res = Regex.Matches(s, "\r\r").Count;


Or a loop over the string:

var res = 0;
for (int i = 0; i < str.Length - 1; i++)
    if(s[i] == '\r' && s[i + 1] == '\r')
        res++;
Magnus
  • 45,362
  • 8
  • 80
  • 118
1

Try this method:

public static int CountStringOccurrences(this string text, string pattern)
{
    int count = 0;
    int i = 0;
    while ((i = text.IndexOf(pattern, i)) != -1)
    {
        i += pattern.Length;
        count++;
    }
    return count;
}

Usage:

int doubleLinefeedCount = sampleString.CountStringOccurrences("\r\r");
Dmitry
  • 13,797
  • 6
  • 32
  • 48
0

You can use LINQ to select all positions where \r\r start and count them:

Enumerable.Range(0, s.Length).Where(idx => s.IndexOf(@"\r\r", idx)==idx).Count();

Note that "\r\r\r" will return 2 in above code...

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • You don't have to use .Where() and then .Count(). The .Count() method itself has an overload with a predicate. See: http://msdn.microsoft.com/en-us/library/vstudio/bb535181(v=vs.110).aspx – Tom Pažourek Apr 19 '14 at 21:17
0

You can use the trick of splitting the string with your lookup charachter \r\r: (this is not really efficient _ we need to allocate 2 string arrays _ but I post it as a possible solution, particularly if the separated tokens are of any interest to you)

"9zogl22n\r\r\nv4bv79gy\r\r\nkaz73ji8\r\r\nxw0w91qq\r\r\ns05jxqxx\r\r\nw08qsxh0\r\r\nuyggbaec\r\r\nu2izr6y6\r\r\n106iha5t\r".Split(new string[] {"\r\r"}, StringSplitOptions.None).Length - 1)
quantdev
  • 23,517
  • 5
  • 55
  • 88
-1

You can write a simple extension method for that:

public static int LineFeedCount(this string source)
{
     var chars = source.ToCharArray();

     bool found = false;
     int counter = 0;
     int count = 0;
     foreach(var ch in chars)
     {
         if (ch == '\r') found = true;
         else found = false;

         if (found) counter++;
         else counter = 0;

         if(counter != 0 && counter%2 == 0) count++;
     }
     return count;
}

Then use it:

int count = inputString.LineFeedCount();
Selman Genç
  • 100,147
  • 13
  • 119
  • 184