Reputation: 3292
string containsCharacter = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(containsCharacter).Length - 1;
I originally pulled this code off another person's question's answer but it doesn't seem to work with text boxes.
Errors I'm getting:
The best overloaded method match for 'string.Split(params char[])' has some invalid arguments
Argument 1: cannot convert from 'string' to 'char[]'
I prefer to fix this code rather than use other things like LINQ but I would accept it if there isn't a way to fix this code.
Upvotes: 1
Views: 137
Reputation: 136
Edit: Upon Reading your code more carefully I suggest you do this, you should rephrase your question to "Check the number of occurences of a certain string in Another string":
string containsString = "this";
string test = "thisisateststringthisisateststring";
var matches = Regex.Matches(test,containsString).Count;
matches is 2!
My initial post answers your actual question "occurrences of a certain character in a string":
string test = "thisisateststring";
int count = test.Count(w => w == 'i');
Count is 3!
Upvotes: 1
Reputation: 4355
You could iterate through the characters
string value = "BANANA";
int x = 0;
foreach (char c in value)
{
if (c == 'A')
x++;
}
Upvotes: 5
Reputation:
The Split
version you are using expects a character as input. This is the version for strings:
string containsText = textBox1.Text;
string testString = "test string contains certain characters";
int count = testString.Split(new string[]{containsText}, StringSplitOptions.None).Length - 1;
With this code, count
will be: 1 if textBox1.Text
includes "test", 6 if it contains "t", etc. That is, it can deal with any string (whose length might be one, as a single character, or as big as required).
Upvotes: 2
Reputation: 1332
"this string. contains. 3. dots".Split(new[] {"."}, StringSplitOptions.None).Count() - 1
Upvotes: 1
Reputation: 726987
You can call ToCharArray
on the string
to make it a char[]
, like this:
int count = testString.Split(containsCharacter.ToCharArray()).Length - 1;
Since Split
takes characters as a param
, you could rewrite this by listing the characters being counted directly, as follows:
int count = testString.Split(',', ';', '-').Length - 1;
Upvotes: 1
Reputation: 2179
string containsCharacter = "t";
string testString = "test string contains certain characters";
int count = testString.Count(x => x.ToString() == containsCharacter);
This example will return 6.
Upvotes: 3