locked
Removing a string from Stringbuilder RRS feed

  • Pergunta

  • Hi,

    I have a collection of strings in stringbuilder object. I want to search a particular string in stringbuilder and if the string exists, I want to remove the searched string.

    Example:

    StrinBuilder object contains:

    A

    B

    C

    D

    E

    If string to be searched is "C", then my strinbuilder should contain without empty space.

    A

    B

    D

    E

    Please let me know better way for this solution.

    Thanks,

    Santosh

    segunda-feira, 24 de agosto de 2020 13:05

Todas as Respostas

  • Going with what you posted for data, run this.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApp1
    {
        class Program
        {
            static void Main(string[] args)
            {
                var findString = "C";
                var builder = new StringBuilder("A\nB\nC\nD\nE");
    
                var resultArray = new List<string>(builder.ToString().Split('\n'))
                    .Where(character => character != findString)
                    .Select(character => $"{character}")
                    .ToArray();
    
                builder = new StringBuilder(string.Join("\n",resultArray));
    
                Console.WriteLine(builder.ToString());
                Console.ReadLine();
            }
        }
    }
    


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    segunda-feira, 24 de agosto de 2020 14:03
  • StringBuilder is just a dynamically increasing buffer for building strings. It's sole purpose is to optimize building strings because strings are immutable so each time you modify it you get a new string. This has negative performance impact if you are "building up" strings, hence the usage of StringBuilder. If you aren't building up a string then you don't need it.

    If you were to append "A", "B", "C", "D", "E" to a bulder then under the hood you'd have a character array with these characters in it. To "remove" the value you'd have to move the rest of the array back one. This isn't going to be cheap. This isn't what StringBuilder was designed for.

    My personal suggestion is that you should detect whether the value ("C" in this case) should be added before you add it. That is what makes StringBuilder useful. When you are conditionally building a string then you determine at the point you need it whether a value is added or not. 

    var builder= new StringBuilder();
    
    builder.Append("A");
    builder.Append("B");
    
    if (someCondition)
       builder.Append("C");
    

    If you cannot do that then StringBuilder may not be the best option. Perhaps you should be using a List<string> instead and build up the list of strings to be added. Then use String.Join to put them together when you're done.

    var items = new List<string>();
    
    items.Add("A");
    items.Add("B");
    
    if (someCondition)
       items.Add("C");
    
    var finalString = String.Join("", items);

    List<string> isn't as efficient as StringBuilder but it allows more flexibility. In this case you can do any standard list manipulation before you join them together. For example if you built the list up and then decided to remove "C" you'd just find and remove it.

    items.Remove("C");
    In my experience conditionally adding to StringBuilder is faster but if I were putting together something like a mailing address or full name from its parts then I'd use List<string>.


    Michael Taylor http://www.michaeltaylorp3.net

    • Sugerido como Resposta Naomi N segunda-feira, 24 de agosto de 2020 17:46
    segunda-feira, 24 de agosto de 2020 14:05
  • Hi

    Simple replace the string if found then replace

       string remove = "C";
                var source = new StringBuilder( "ABCDE").Replace(remove, null);

    Thanks and regards

    segunda-feira, 24 de agosto de 2020 16:47
  • Funny, Karen - I had in mind exactly the same solution you posted (split and join) and thought it's not going to be performant, so I'll wait for other posters :)


    Looking for new opportunities

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    segunda-feira, 24 de agosto de 2020 17:45
  • Funny, Karen - I had in mind exactly the same solution you posted (split and join) and thought it's not going to be performant, so I'll wait for other posters :)


    Looking for new opportunities

    For every expert, there is an equal and opposite expert. - Becker's Law


    My blog


    My TechNet articles

    And I was thinking what CoolDadTx mentioned about being proactive LOL. Funny how things go.

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    segunda-feira, 24 de agosto de 2020 18:42
  • Hi,

    Has your issue been resolved?

    If so, please click on the "Mark as answer" option of the reply that solved your question, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    quinta-feira, 3 de setembro de 2020 09:42