1

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 multi line 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);
5
  • @S.Akbari There you go: imgur.com/a/LQhsz Commented Sep 30, 2017 at 16:15
  • Firstly, you're not trying to count the occurrences of InputSingleLine - you're trying to count the occurrences of SingleLineTxtBox, which makes no sense. Next, you should try to count the occurrences of a character, not a string - so you want something like char characterToFind = SingleLineTxtBox.Text[0]; (after checking that there is actually a single character there). Then you can use int count = InputMultiLine.Count(f => f == characterToFind);. As an aside, I'd strongly recommend learning about C# naming conventions as early as possible to avoid getting into bad habits. Commented Sep 30, 2017 at 16:17
  • @JonSkeet But what if SingleLineTxtBox is empty? Using char characterToFind = SingleLineTxtBox.Text[0]; will throw Index was outside the bounds of the array.' Commented Sep 30, 2017 at 16:48
  • @S.Akbari: Hence the "after checking that there is actually a single character there" part of my comment. Commented Sep 30, 2017 at 16:55
  • @JonSkeet Right. I didn't noticed this part of your comment inside parenthesis. Commented Sep 30, 2017 at 16:56

3 Answers 3

1

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Using FirstOrDefault means it'll look for U+0000 if the text box is empty. Surely it would be better just to detect that and not look.
0
string sentence = "You might be surprised to learn that";
char singleChar = 'i';
int count = sentence.Count(f => f == singleChar);

PS: Only in .NET 3.5

Comments

-1
string pattern = string.Format("^{0}$", InputSingleline);
int count = Regex.Matches(InputMultiline, pattern).Count;

1 Comment

While this code may answer the question, it's probably better to include more context/explanation. (I didn't downvote BTW).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.