Quantity of a given character contained in a StringBuilder

2

I have a StringBuilder with these values: 12 ********** 3 * 4 *.

Is there a simple way to return the number of asterisks without having to load a string on top of my StringBuilder?

I'm using C # with Net Framework 3.5

    
asked by anonymous 17.07.2014 / 19:12

2 answers

3

One possible solution:

StringBuilder valor = new StringBuilder("12**********3*4*");
int total = valor.Length - valor.Replace("*", "").Length;

Remember that any method used will have to look for the character inside the string, similar to an iteration. Due to internal optimizations, some methods may be faster than others. The only way to check this is by testing and comparing each of the methods. In general, the minimum complexity for this type of operation is O (n) , where n is the length of the string.

    
17.07.2014 / 19:21
4

Using Linq you can get the amount of characters that are asteristical as follows:

StringBuilder builder = new StringBuilder("12**********3*4*");

// É necessário usar ToString() para evitar chamar métodos que alteram o conteúdo do
// StringBuilder durante o processo de contagem dos caracteres, pois caso contrário
// isso poderia ter efeitos colaterais inesperados.
int totalDeAsteristicos = builder.ToString().Count(x => x =='*');
    
17.07.2014 / 19:29