Hi, how do I count characters in a string with C#?
string.Length;
Your millage may vary and this can be done a lot of ways and Length is the right choice, but here you go.
using System;
public class SillyStringQuestion
{
private string sentence;
public SillyStringQuestion(string theString)
{
this.sentence = theString;
}
public int CountCharsTheString()
{
int result = 0;
if(!string.IsNullOrWhiteSpace(sentence))
{
charArray = sentence.ToCharArray();
foreach(char character in charArray)
result++;
}
else
{
throw new Exception("bummer no data and stuff");
}
return result;
}
}
For those that are interested, this website has benchmarked at least a dozen different ways to count the number of times a character occurs in a string, using both single threaded and multithreaded techniques.
Basically, the winner is either the single or parallel for-loop implementations as follows where “ss” is the Search String, “ch” is the array of characters you’re looking for.:
for (int x = 0; x < ss.Length; x++)
{
for (int y = 0; y < ch.Length; y++)
{
for (int a = 0; a < ss[x].Length; a++ )
{
if (ss[x][a] == ch[y])
//it's a match. Do what you need to.
}
}
}