1084

I want to count how many /s I could find in a string. There are several ways to do it, but I couldn't decide on what the best (or easiest) is.

At the moment I'm going with something like:

string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;

Or for strings where length > 1:

string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
0

37 Answers 37

1
2
1
str="aaabbbbjjja";
int count = 0;
int size = str.Length;

string[] strarray = new string[size];
for (int i = 0; i < str.Length; i++)
{
    strarray[i] = str.Substring(i, 1);
}
Array.Sort(strarray);
str = "";
for (int i = 0; i < strarray.Length - 1; i++)
{

    if (strarray[i] == strarray[i + 1])
    {

        count++;
    }
    else
    {
        count++;
        str = str + strarray[i] + count;
        count = 0;
    }

}
count++;
str = str + strarray[strarray.Length - 1] + count;

This is for counting the character occurance. For this example output will be "a4b4j3"

Sign up to request clarification or add additional context in comments.

2 Comments

Not quite 'counting occurrences of a string' more counting characters - how about a way of specifying what the string to match was Narenda?
int count = 0; string str = "we have foo and foo please count foo in this"; string stroccurance="foo"; string[] strarray = str.Split(' '); Array.Sort(strarray); str = ""; for (int i = 0; i < strarray.Length - 1; i++) { if (strarray[i] == stroccurance) { count++; } } str = "Number of occurenance for " +stroccurance + " is " + count; Through this you can count any string occurance in this example I am counting the occurance of "foo" and it will give me the output 3.
1

**to count char or string **

 string st = "asdfasdfasdfsadfasdf/asdfasdfas/dfsdfsdafsdfsd/fsadfasdf/dff";
        int count = 0;
        int location = 0;
       
        while (st.IndexOf("/", location + 1) > 0)
        {
                count++;
                location = st.IndexOf("/", location + 1);
        }
        MessageBox.Show(count.ToString());

Comments

0
string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)
   if (s[i] == 'H') count++;

It just checks every character in the string, if the character is the character you are searching for, add one to count.

Comments

0

For the case of a string delimiter (not for the char case, as the subject says):
string source = "@@@once@@@upon@@@a@@@time@@@";
int count = source.Split(new[] { "@@@" }, StringSplitOptions.RemoveEmptyEntries).Length - 1;

The poster's original source value's ("/once/upon/a/time/") natural delimiter is a char '/' and responses do explain source.Split(char[]) option though...

Comments

0

Looking for char counts is a lot different than looking for string counts. Also it depends if you want to be able to check more than one or not. If you want to check a variety of different char counts, something like this can work:

var charCounts =
   haystack
   .GroupBy(c => c)
   .ToDictionary(g => g.Key, g => g.Count());

var needleCount = charCounts.ContainsKey(needle) ? charCounts[needle] : 0;

Note 1: grouping into a dictionary is useful enough that it makes a lot of sense to write a GroupToDictionary extension method for it.

Note 2: it can also be useful to have your own implementation of a dictionary that allows for default values and then you could get 0 for non-existent keys automatically.

Comments

0

string charters= "aabcbd":

char[] char = charters.TocharArary(); List lst = new List();

for(int i=0; i< char.Length; i++)
{
    if(!lst.Contains(char[0]))
    {
        int count = charters.Where(x=> x.value == char[0]).Count;
        lst.Add(char[0]);
        Console.WriteLine($"{char[0]} occures {count} times");
    }
}

Output will be as below: a occures 2 times b occures 2 times c occures 1 times d occures 1 times

Comments

-1

SearchValues

Using the new C# SearchValues is super-duper-fast, inside the .Net Framework MSFT has replaced all their search lookups to use SearchValues.

Chars:

public static void Main()
{
    string source = "/once/upon/a/time/";
    char searchChar = '/';

    int count = CountOccurrences(source, searchChar);
    Console.WriteLine($"The character '{searchChar}' occurs {count} times.");
}

public static int CountOccurrences(string source, char searchChar)
{
    ReadOnlySpan<char> span = source.AsSpan();
    var searchValues = SearchValues.Create(new[] { searchChar });

    int count = 0;
    foreach (int index in searchValues.Search(span))
    {
        count++;
    }

    return count;
}

Strings:

public static int CountOccurrences(string source, string searchString)
{
    if (string.IsNullOrEmpty(searchString))
    {
        return 0;
    }

    ReadOnlySpan<char> span = source.AsSpan();
    ReadOnlySpan<char> searchSpan = searchString.AsSpan();
    int count = 0;
    int index;

    while ((index = span.IndexOf(searchSpan)) != -1)
    {
        count++;
        span = span.Slice(index + searchSpan.Length);
    }

    return count;
}

Comments

1
2

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.