• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 198
  • Last Modified:

C# Code to find the number of "-" in a string

Need C# code to find the number of "-" in a string,

Input:  AS-VF, DE-W3
Expected Result = 2

Just need to count the NBR of dashes in a string.
1 Solution
käµfm³d 👽Commented:
Code-wise, the simplest might be:

int count = source.Split('-').Length - 1;

Open in new window

You could also do:

using System.Linq;


int count = source.Where(c => c == '-').Count();

Open in new window


int count = GetCharCount(source, '-');


int GetCharCount(string source, char targetChar)
    int count = 0;

    for (int i = 0; i < source.Length; i++)
        if (source[i] == targetChar) count++;

    return count;

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now