Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is correct way to a remove few characters at the end of string C#

Tags:

c#

asp.net

Consider the following code, what is the correct way to a remove the last two <br/> tags from the end of string in C#? I have followed very naive method, to achieve this. Can you please suggest improvements.

List<string> MessageList; // populated from data source
Label lblHtmlOutput = new Label();
StringBuilder sb = new StringBuilder();
foreach (var item in MessageList)
{
    sb.Append(item + "<br/><br/>");
}
sb.Remove(sb.Length - 11, sb.Length - 1);
like image 599
Abhijeet Avatar asked Nov 28 '25 06:11

Abhijeet


2 Answers

Don't add them in the first place. Use something like:

String.Join("<br/><br/>", MessageList);
like image 92
Scott Avatar answered Nov 30 '25 20:11

Scott


Don't insert them in the first place:

    List<string> MessageList; // populated from data source
    Label lblHtmlOutput = new Label();
    //StringBuilder sb = new StringBuilder();
    //foreach (var item in MessageList)
    //{
    //    sb.Append(item + "<br/><br/>");
    //}
    //sb.Remove(sb.Length - 11, sb.Length - 1);
    string list = string.Join("<br/><br/>", MessageList);
like image 22
Henk Holterman Avatar answered Nov 30 '25 18:11

Henk Holterman