Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » C# Language » Custom String Methods using C#

Custom String Methods using C#

In this article I will explain you about the Custom String Methods using C#.

Author Rank :
Page Views : 4961
Downloads : 43
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
CustomString.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Puran Mehra

Working as a Software professional. 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
PCase redux.... by james.curran On February 1, 2010
Sorry if this is a repeat... I'm not sure if the first comment made it....
Besides being simpler & easier to understand, this is sgnificantly faster:

public static String PCase2(String strParam)

{

StringBuilder sb = new StringBuilder(strParam.Length);

char cPrev = '.'; // start with something to force the next character to upper.

foreach(char c in strParam)

{

if (cPrev == '.' || Char.IsWhiteSpace(cPrev))

sb.Append(Char.ToUpper(c));

else

sb.Append(Char.ToLower(c));

cPrev = c;

}

return sb.ToString();

}

Reply | Email | Modify 
ditto for Reverse by james.curran On February 1, 2010

public static String Reverse2(String strParam)

{

byte[] rev = Encoding.ASCII.GetBytes(strParam);

Array.Reverse(rev);

return Encoding.ASCII.GetString(rev);

}

Reply | Email | Modify 
And CharCount by james.curran On February 1, 2010
This one's only slightly faster

public static int CharCount2(String strSource, String strToCount)

{

int iCount = 0;

int iPos = strSource.IndexOf(strToCount);

while (iPos != -1)

{

iCount++;

iPos = strSource.IndexOf(strToCount, iPos+1);

}

return iCount;

}

Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.