locked
find out the number of ',' RRS feed

  • Question

  • Hi Friends,

                      I have a sting(For eg:a,b,c,d)..How to write a c# code to find out the number of ',' ( comma's)  in the string

    Wednesday, July 21, 2010 11:21 AM

Answers

  •      
    public int GetCommaCount(string s)
    {
     string s = "a,b,c,d)..";
    
          int iCommaCount = s.Split(new char[] {','}).Length - 1;
          return iCommaCount;
    }
    • Proposed as answer by Jesse HouwingMVP Wednesday, July 21, 2010 12:11 PM
    • Marked as answer by Hari nvp Wednesday, July 21, 2010 2:03 PM
    Wednesday, July 21, 2010 11:34 AM

All replies

  •      
    public int GetCommaCount(string s)
    {
     string s = "a,b,c,d)..";
    
          int iCommaCount = s.Split(new char[] {','}).Length - 1;
          return iCommaCount;
    }
    • Proposed as answer by Jesse HouwingMVP Wednesday, July 21, 2010 12:11 PM
    • Marked as answer by Hari nvp Wednesday, July 21, 2010 2:03 PM
    Wednesday, July 21, 2010 11:34 AM
  • Hi,

     

    Use Regex function. Like below code,

     

    using System.Text.RegularExpressions;

    ..... // your code

     

                String st = "a,b,c,d";
                int countVal = Regex.Matches(st, ",").Count;

    Wednesday, July 21, 2010 11:39 AM
  • hello hari software poet,

    You can use

    1) string.indexof() method recursively.... or

    2) use string.split(',') function , which returns array of strings ...

        no. of comma in string =  return  string array - 1 ;-)

     

    may be it helps u...

    If anything is unclear feel free to ask me...

    Thanks,

    Nans11

    Wednesday, July 21, 2010 11:45 AM
  • Hi,

    If you're using C# or later, you could also use LINQ. Like the following code snippet:

    var count = (from c in testString
           where c.Equals(',')
           select c).Count();
    
    

    Here testString contains your string. You could also use the extension methods directly like so:

    count = testString.Where(c => c.Equals(',')).Count();
    
    

    The advantage of this over the other mentioned solutions, is that in the case of using LINQ you leave it up to the compiler to decide how to do the processing under the hood.

    Hope this helps.
    Meile Zetstra


    http;//blogger.xs4all.nl/mzetstra

    Wednesday, July 21, 2010 12:13 PM
  • You can also do this using LINQ, I find this th emost logical way (as in most readable):

     

     

    string x = "a,b,c,d,e";
    int count = x.ToCharArray().Count(c=> c== ',');

    Or even better:

    count = x.Count(c => c == ',');

    • Proposed as answer by Jesse HouwingMVP Wednesday, July 21, 2010 12:17 PM
    • Edited by Jesse HouwingMVP Wednesday, July 21, 2010 12:20 PM Improved solution using LINQ
    Wednesday, July 21, 2010 12:17 PM