Amount of a given character contained in a Stringbuilder

Asked

Viewed 917 times

2

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

There is a simple way to return the amount of asterisks without having to do a go over my Stringbuilder?

I’m using C# with Net Framework 3.5

2 answers

4

Using Linq you can get the amount of characters that are asterisked 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 =='*');
  • 1

    +1, I find this way much more readable.

  • Thanks, @dcastro Besides being more readable, this form does not modify the contents of the Builder. The answer marked as accepted may bring unwanted side effects by fully altering the contents of the Builder only to obtain the amount of a certain character.

3


A possible solution:

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

It is worth remembering 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 verify this is by testing and comparing each of the methods. In general, the minimum complexity for this type of operation will be O(n), where n is the string size.

  • 1

    No need to pass to String: StringBuilder builder = new StringBuilder("12**********3*4*"); int total = builder.Length - builder.Replace("*", "").Length;

  • True Peter, I have changed as you suggest.

  • I believe that there is a problem in this answer, because when you call the Builder method. Replace() you are changing the text of the Builder, and in my opinion a query operation should never modify the content of the one being consulted, because otherwise the result of the query will no longer represent the reality or original state of the data that were consulted. In this specific case, for example, after the operation you will know how many asterisms the Builder TINHA, but after the operation the Builder will no longer have any asterisms.

  • Hi @Ulyssesalves, I find your comment valid, but this will depend entirely on how the code will be used. Probably, the string "12********34" comes from another location, and so will not be changed with the Replace call in the Stringbuilder object. If it is the original string, something unlikely, just call the Tostring method before calling the Replace method.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.