C# StringBuilder and Splitting Strings

StringBuilder and Splitting Strings

// The StringBuilder Class
StringBuilder sb = StringBuilder("Pineapple");
sb.Replace(‘e’, ‘X’);                        // "PinXapplX"
sb.Insert(4, "Banana");                      // "PinXBananaapplX"
sb.Append("Kiwi");                      // "PinXBananaapplXKiwi"
sb.AppendFormat(", {0}:{1}", 123, 45.6789);  // "PinXBananaapplXKiwi, 123, 45.6789"
sb.Remove(sb.Length – 3, 3);                 // "PinXBananaapplXKiwi, 123, 45.6"
Console.WriteLine(sb.ToString().ToUpper());  // "PINXBANANAAPPLXKIWI, 123, 45.6"

// Splitting Strings
string s = "Once:Upon*A?Time<In>America";
char[] seps = new char[]{’\\’, ‘/’, ‘:’, ‘*’, ‘?’, ‘\"’, ‘|’, ‘<‘, ‘>’};
foreach (string ss in s.Split(seps))
    Console.WriteLine(ss);

// Note: Not very useful when trying to split substrings by multiple instances of some character.
string u = "Once___Upon A Time___In America";
char[] sep2 = new char[]{’_‘};
foreach (string ss in u.Split(sep2))
    Console.WriteLine(ss);    // "Once", "___", "Upon A Time", "___", "In America"

// Note: Split by one or more occurances of whitespace.
Regex o = new Regex(@"[\s]+");
foreach (string ss in o.Split(u))
    Console.WriteLine(ss);   // "Once", "Upon A Time", "In America"

// ProperCase
public static string ProperCase(string s)
{
    s = s.ToLower();
    string sProper = "";
    char [] seps = new char[]{’ ‘};
    foreach (string ss in s.Split(seps))
    {
        sProper += char.ToUpper(ss[0]);
        sProper += (ss.Substring(1, ss.Length – 1) + ‘ ‘);
    }
    return sProper;
}

// IsPalindrome
public static bool IsPalindrome(string s)
{
    int iLength, iHalfLen;
    iLength = s.Length – 1;
    iHalfLen = iLength / 2;
    for (int i = 0; i <= iHalfLen; i++)
    {
        if (s.Substring(i, 1) != s.Substring(iLength – i, 1)
        {
            return false;
        }
    }
    return true;
}

// Conditional

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s