Delimited string helper class in C#

Build delimited strings with less code!

Having to build a string with elements delimited with special characters for a CSV file, a HTTP GET request or any other purpose?
How many times did you made a loop to construct the string, having to user a flag to check if the delimiter have to be added, either at the beginning or the end or the string, to make sure chere is not an intrusive delimiter in the result? To make sure the string don't have the delimiter at the beginning or at the end?

This simple class uses a StringBuilder to construct a key / value string delimited with a given character or string just between elements.


using System;
using System.Text;


/// <summary>
/// To construct a string delimited only between elements.
///
/// Simple helper class to construct dynamically a delimited string
/// with the delimiter inserted automatically only between elements,
/// not at the beginnig nor at the end of the resulting string.
///
/// Uses a StringBuilder as the inner builder.
/// Denis Sauvé
/// </summary>
public class DelimitedStringBuilder
{
protected string delimiter = null;
protected StringBuilder sb = new StringBuilder();
// inner StringBuilder, as StringBuilder class cannot be inherited
/// <summary>
/// New instance of a DelimitedStringBuilder with delimiter between elements
/// </summary>
/// <param name="delimiter">delemiter to use (",", "\n", etc)</param>
public DelimitedStringBuilder(string delimiter)
{
this.delimiter = delimiter;
}
public void Append(string stringToAppend)
{
if (sb.Length >0)
if (delimiter != null) sb.Append(delimiter);
sb.Append(stringToAppend);
}
public override string ToString()
{
return sb.ToString();
}
public StringBuilder InnerStringBuilder
{
get
{
return this.sb;
}
}

}


Note: you have to make sure the delimiter is not in the keys nor in the values... But tThe Append() method could be modified easilly to check that.

3 comments:

Anonymous said...

viagra generic soft tab viagra prices how does viagra work viagra online uk non prescription viagra cheap generic viagra too much viagra viagra canada soma and viagra prescriptions free viagra uk alternative viagra splitting viagra viagra free pills viagra faq try viagra for free

Anonymous said...

[url=http://kfarbair.com][img]http://www.kfarbair.com/_images/_photos/photo_big8.jpg[/img][/url]

בית מלון [url=http://www.kfarbair.com]כפר בעיר[/url] - אינטימיות, [url=http://kfarbair.com/services.html]שקט[/url] . אנו מציעים שירותי אירוח מגוונים כמו כן יש במקום שירות חדרים הכולל [url=http://www.kfarbair.com/eng/index.html]סעודות רומנטיות[/url] במחירים מיוחדים אשר מוגשות ישירות לחדרכם!

לפרטים נוספים אנא גשו לאתרנו - [url=http://kfarbair.com]כפר בעיר[/url] [url=http://www.kfarbair.com/contact.html][img]http://www.kfarbair.com/_images/apixel.gif[/img][/url]

Anonymous said...

buy xanax best kind xanax bars - xanax 1mg value