We help IT Professionals succeed at work.

I need to count number of '<' in a String

I am doing string parsing of a Razor file and need to use the Count() function to count the number of opening tags and closing tags on one line.

How can I do this? I think the Count() funtion will work, but I am not sure of the input param.

Thanks,
newbieweb
Comment
Watch Question

Research & Development Manager
Commented:
You can use a predicate expression:
string mystring = "a<b<c";
int count = mystring.Count(f => f == '<');
Console.WriteLine(count.ToString());

Open in new window

Most Valuable Expert 2011
Top Expert 2015

Commented:
You'll probably have to call ToCharArray on the string variable before calling Count in Tchuki's example.
curiouswebsterSoftware Engineer

Author

Commented:
Could you show where that would go?
Most Valuable Expert 2011
Top Expert 2015
Commented:
int count = mystring.ToCharArray().Count(f => f == '<');

Open in new window

Vel EousResearch & Development Manager
Commented:
If you are reading from a file you could use the following:
string pathSource = @"c:\tests\source.txt";
int flags = 0;
try
{
  using (StreamReader reader = new StreamReader(pathSource))
  {
    string line;
    while ((line = reader .ReadLine()) != null)
    {
      Console.WriteLine(line);
      flags += line.ToCharArray().Count(f => f == '<' || f == '>');
    }
    Console.WriteLine(flags);
  }
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
}

Open in new window

string.length-replace(string,"<","").length
Commented:
put the file contents in a string or string[]
each string s is counted for opening and closing tags like:

            int closingTags = s.Split(new[] {"</"}, StringSplitOptions.None).Length - 1;
            int openingTags = s.Split(new[] { '<' }).Length - closingTags - 1;
            Console.WriteLine( "open={0} close={1}", openingTags, closingTags);
curiouswebsterSoftware Engineer

Author

Commented:
Thanks.