Feudelcosine148 Feudelcosine148 - 3 years ago 212
C# Question

Check character from input count occurance in String C#

I'm new to C#, and I'm trying to figure something out.
I'm trying to count the occurrence of a single digit to that in a string.
What I mean by this is The user types in a sentence in a multiline textbox and below in a separate text field a single letter. I need to check how many times that single letter occurs in the sentence.

Currently, I have the input of the two text fields by using this

string InputSingleline = SingleLineTxtBox.Text;
string InputMultiline = MultiLineTxtBox.Text;


And I'm trying to count the occurance of input in "InputSingleLine" in "MultiLineTxtBox" by using this but it does not work.

int Count = InputMultiline.Count(f => f == SingleLineTxtBox);


Sorry if my explanation is hard to understand, but this is the best I could describe it.

Answer Source

Firstly you should count the occurrences of InputSingleline instead of SingleLineTxtBox since you have already set the InputSingleline to SingleLineTxtBox.Text. And secondly the InputSingleline is a string with one character, so you need to use something like FirstOrDefault to return that character from this string:

int Count = InputMultiline.Count(f => f == InputSingleline.FirstOrDefault());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download