Monday, May 24, 2010

Can someone give me an algorithm in C# to obtain and get the number of occurences of a unique char in a string

You can use regular expressions or a series of IndexOf calls.





Assuming,


string searchString = "abcbdefb";


char charToFind = 'b';





Regular Expressions:


int numberOfChars = System.Text.RegularExpressions .Regex.Matches( searchString, charToFind.ToString() ).Count;





IndexOf:


int numberOfChars = 0;


int lastIndex = 0;


while(lastIndex %26lt; searchString.Length %26amp;%26amp; lastIndex %26gt; -1)


{


lastIndex = searchString.IndexOf( charToFind, lastIndex + 1);


if (lastIndex == -1) break;


numberOfChars++;


}

Can someone give me an algorithm in C# to obtain and get the number of occurences of a unique char in a string
Well for VB, its like Len("msg") or Len(TextBox1.Text) and it tells you how many characters are in that text box.


No comments:

Post a Comment