Custom String Methods using C#


This article has been excerpted from book "The Complete Visual C# Programmer's Guide" from the Authors of C# Corner.

Below are some custom string methods for C# that are found in VB.NET and various scripting languages: PCase, Replace, ToSingleSpace, CharCount, Reverse, Left, Right, and IsPalindrome. These methods are useful in common string operations. Since the .NET Framewrk does not natively include these methods, you can use the methods in Listing 20.32 to build your own "super string" class. Let's start with the code, then explain it in detail. 

Listing 20.32:  Auxiliary Custom String Methods 

// Auxiliary custom String methods
using System;

class MyString
{
    public static void Main()
    {
        String strData = "WeLcOmE tO c#.eNjoy FoLkS";
        Console.WriteLine("String Value: {0}", strData);
        Console.WriteLine("PCase Equivalent: {0}", PCase(strData));
        Console.WriteLine("Reverse Equivalent: {0}", Reverse(strData));
        Console.WriteLine("Is 'rotator' PalinDrome: {0}", IsPalindrome("rotator"));
        Console.WriteLine("Is 'visualc#' PalinDrome: {0}", IsPalindrome("visualc#"));
        Console.WriteLine("Left(string,5): {0}", Left(strData, 5));
        Console.WriteLine("Right(String,6): {0}", Right(strData, 6));
        Console.WriteLine("CharCount(Charcount,c):{0}", CharCount("Charcount", "C"));
        Console.WriteLine("CharCount(CharCount,c,true):{0}", CharCount("Charcount", "C", true));
        Console.WriteLine("CharCount(CharCount,d,true):{0}", CharCount("Charcount", "d", true));
        Console.WriteLine("ToSingleSpace('welcome to C Sharp'): {0}", ToSingleSpace("welcome to C Sharp "));
        Console.WriteLine("Replace(aaaaaa,aa,a):{0}", Replace("aaaaaa", "aa", "a"));
        Console.ReadLine();
    }

    // Convert String to ProperCase
    public static String PCase(String strParam)
    {
        String strProper = strParam.Substring(0, 1).ToUpper();
        strParam = strParam.Substring(1).ToLower();
        String strPrev = "";

        for (int iIndex = 0; iIndex < strParam.Length; iIndex++)
        {
            if (iIndex > 1)
            {
                strPrev = strParam.Substring(iIndex - 1, 1);
            }

            if (strPrev.Equals(" ") ||
            strPrev.Equals("\t") ||
            strPrev.Equals("\n") ||
            strPrev.Equals("."))
            {
                strProper += strParam.Substring(iIndex, 1).ToUpper();
            }
            else
            {
                strProper += strParam.Substring(iIndex, 1);
            }
        }
        return strProper;
    }

    // Replace string with a found string in the source string
    public static String Replace(String strText, String strFind, String
    strReplace)
    {
        int iPos = strText.IndexOf(strFind);
        String strReturn = "";

        while (iPos != -1)
        {
            strReturn += strText.Substring(0, iPos) + strReplace;
            strText = strText.Substring(iPos + strFind.Length);
            iPos = strText.IndexOf(strFind);
        }

        if (strText.Length > 0)
            strReturn += strText;
        return strReturn;
    }

    // Trim the string to contain only a single whitepace between words
    public static String ToSingleSpace(String strParam)
    {
        int iPosition = strParam.IndexOf(" ");
        if (iPosition == -1)
        {
            return strParam;
        }
        else
        {
            return ToSingleSpace(strParam.Substring(0, iPosition) +
            strParam.Substring(iPosition + 1));
        }
    }

    // Count the number of occurrences of a substring in a source string
    // case sensitive
    public static int CharCount(String strSource, String strToCount)
    {
        int iCount = 0;
        int iPos = strSource.IndexOf(strToCount);

        while (iPos != -1)
        {
            iCount++;
            strSource = strSource.Substring(iPos + 1);
            iPos = strSource.IndexOf(strToCount);
        }
        return iCount;
    }

    // Count the number of occurrences of a substring in a source string
    // case insensitive
    public static int CharCount(String strSource, String strToCount, bool IgnoreCase)
    {
        if (IgnoreCase)
        {
            return CharCount(strSource.ToLower(), strToCount.ToLower());
        }
        else
        {
            return CharCount(strSource, strToCount);
        }
    }

    // Reverse the String passed

    public static String Reverse(String strParam)
    {
        if (strParam.Length == 1)
        {
            return strParam;
        }
        else
        {
            return Reverse(strParam.Substring(1)) + strParam.Substring(0, 1);
        }
    }

    // Get a number of characters of a string from the beginning
    public static String Left(String strParam, int iLen)
    {
        if (iLen > 0)
            return strParam.Substring(0, iLen);
        else
            return strParam;
    }

    // Get a number of characters of a string from then end
    public static String Right(String strParam, int iLen)
    {
        if (iLen > 0)
            return strParam.Substring(strParam.Length - iLen, iLen);
        else
            return strParam;
    }

    // Test if the string is Palindrome
    public static bool IsPalindrome(String strParam)
    {
        int iLength, iHalfLen;
        iLength = strParam.Length - 1;
        iHalfLen = iLength / 2;

        for (int iIndex = 0; iIndex <= iHalfLen; iIndex++)
        {
            if (strParam.Substring(iIndex, 1) != strParam.Substring(iLength - iIndex, 1))
            {
                return false;
            }
        }
        return true;
    }
}

Output of above code:

customstrings.gif

The PCase method converts a string to proper case, capitalizing each word's first character. It distinguishes words using whitespace characters such as space, tab, line feed, and carriage return characters ( ' ', '\t', '\n', '\r'). Its usage is PCase(String). 

The Replace method replaces strings with string phrases and characters. This function finds characters passed in the second argument within the source string in the first argument and replaces them with characters in the third argument. Its usage is Replace(Source, Find, Replacement). For example, Replace("abc","b","d") will return "adc". 

The ToSingleSpace function converts multiple whitespace characters to single whitespace characters. Its usage is ToSingleSpace(SourceString). For example, ToSingleSpace("Welcome to C#") will return "Welcome to C#". 

The CharCount method returns the number of occurrences of a substring in the main string. CharCount has two overloads: one for case-sensitive operations and the other for case-insensitive operations. For case-insensitive operations, CharCount simply converts both string and substring parameters to full lowercase, then calls the case-sensitive CharCount method. The CharCount method can be useful for string-parsing operations. CharCount usages are CharCount(Source, Find) or CharCount(Source, Find, true). For example, CharCount("aaaaac", "a") and CharCount("aaaaac","A", true) will return 5, but CharCount("aaaaac", "A") and CharCount("aaaaac", "A", false) will return 0. 

The Reverse method reverses and returns the characters in a string argument. Its usage is Reverse(Source). For example, Reverse("abc") will return cba. 

The Left method returns a certain number of characters from the beginning, or left side, of the string. Its usage is Left(Source, CharCount). For example, Left("Welcome", 3) will return Wel. 

The Right method returns a certain number of characters from the end, or right side, of the string. Its usage is Right(Source, CharCount). For example, Right("Welcome", 2) will return me. 

The IsPalindrome function returns whether the passed string is a palindrome reading the same backward as forward. Its usage is IsPalindrome(Source). For example, IsPalindrome("abc") will return false, whereas IsPalindrome("121") will return true. 

Conclusion

Hope this article would have helped you in understanding Custom String Methods using C#. See other articles on the website on .NET and C#.

visual C-sharp.jpg
The Complete Visual C# Programmer's Guide covers most of the major components that make up C# and the .net environment. The book is geared toward the intermediate programmer, but contains enough material to satisfy the advanced developer.


Recommended Free Ebook
Similar Articles