Strings in C# - Part 2


Introduction
 
String (string) is an alias type of the System.String class. This class provides a set of methods for working with strings. Let's list some of them that we will cover in this article.

PadLeft()/PadRight(): Returns copies of the current string that has been padded with specific data.

Remove()/Replace(): Receives copy of string with modifications. Deletes a specified number of characters from this instance beginning at a specified position.

Split(): Separates strings by a specified set of characters and places these strings into an array of strings.

Trim(): Trim method removes white spaces from the beginning and end of a string.

TrimStart(): Selectively removes a series of characters from the starting position.

TrimEnd(): Remove all trailing punctuations from string.

Substring(): Returns a string that represents a substring of the current string.
ToCharArray(): Returns a character array representing the current string.

Let's discuss about all of them above.
PadLeft()/PadRight() Methods
 
In C#, PadLeft and PadRight methods can be used to insert characters or can be used to add characters to the beginning and end of text.
 
Let's look at program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Simple Use
            string str1 = "Abhimanyu";
            str1 = str1.PadLeft(20);
            Console.WriteLine(str1);
 
            string str2 = "Kumar";
            str2 = str2.PadRight(30);
            Console.WriteLine(str2);  //it will not be visible as it is very close to axis
 
            //Padding with symbol
            string str3 = "Vatsa";
            char padWith = '*';
            Console.WriteLine(str3.PadLeft(20, padWith));
 
            string str4 = "Good Luck";
            char padWith1 = '-';
            Console.WriteLine(str4.PadLeft(10, padWith1));
 
            Console.ReadKey();
        }
    }
}
 
The above code will produce the following output:
 
image002.jpg
 
Remove()/Replace() Methods
 
As both names suggest, Remove is used to remove characters from a string and Replace is used to replace the characters from string. This is often more useful with StringBuilder.
 
Let's look at program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Remove
            string str1 = "abhimanyu";
            str1 = str1.Remove(str1.Length - 1);  //Remove(total_length - 1) means will not display last word
            Console.WriteLine(str1);
 
            string str2 = "kumar";
            str2 = str2.Remove(0, 2);  //Remove(start_location, number_of_digit_to_remove)
            Console.WriteLine(str2);
 
            //Using Replace
            string str3 = "abhimanyu kumar";
            Console.WriteLine(str3);
 
            string str4 = str3.Replace("kumar""kumar vatsa");
            Console.WriteLine(str4);
 
            Console.ReadKey();
        }
    }
}
 
The above code will produce the following output:
 
image004.jpg
 
Split() Method
 
Separates strings by a specified set of characters and places these strings into an array of strings. Assume, if you want to split strings on different characters with single character or string delimiters. For example, split a string that contains "\r\n" sequences, which are Windows newlines.
 
Let's look at program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Split normally
            string str1 = "abhimanyu kumar vatsa";
            string[] newWordLines = str1.Split(' '); //this will create array of string
            foreach (string word in newWordLines)
            {
                Console.WriteLine(word);
            }
 
            //Using Split using method1
            string str2 = "abhimanyu,dhananjay,sam,suthish,sam";
            foreach (string s in Split1(str2, ',')) //Calling Method1 each time
               {
                   Console.WriteLine(s);
               }
 
            //Using Split using method2
            string str3 = "09-08-2011";
            Console.WriteLine(str3);
            str3 = str3.Replace('-''/');
            Console.WriteLine(str3);
            foreach (string s in Split2(str3, '/'))
            {
                Console.WriteLine(s);
            }
 
            Console.ReadKey();
        }
 
        //Method1
        static string[] Split1(string value, char delimiter)
        {
            return value.Split(delimiter);
        }
 
        //Method2
        static string[] Split2(string value, char delimiter)
        {
            return value.Split(delimiter);
        }
    }
}
 
The above code will produce the following output:
 
image006.jpg
 
Trim() Method
 
Sometimes we need to remove white spaces or new lines from the beginning or ending of string, C# provides Trim() method for this.
 
Let's look at program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;  //for file input/output
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using Trim() for white spaces
            string str1 = "  abhimanyu kumar vatsa. ";
            str1 = str1.Trim();
            Console.WriteLine(str1);
           
            //Now line trim
            string str2 = "abhimanyu kumar vatsa\r\n\r\n";
            Console.WriteLine("{0}.",str2);  //check dot(.) location on console
            str2 = str2.Trim();  //let's trim
            Console.WriteLine("{0}.",str2);  //now check dot(.) locatiion on console
 
            //Line trim in file
            foreach (string lines in File.ReadAllLines("abhimanyu.txt"))
            {
                Console.WriteLine("*" + lines + "*");  //before trim
                string trimmed = lines.Trim();
                Console.WriteLine("*" + trimmed + "*");  //after trim
            }
            Console.ReadKey();
        }
    }
}
 
Above code will produce the following output:
 
image008.jpg
 
TrimStart() Method
 
This is much simpler to understand. Assume you want to selectively remove a series of characters from the starting position (remember only from a starting position) of a string then C# has a method for you that is TrimStart() method.
 
Let's look at the program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using TrimStart()
            string str1 = ".\t,   abhimanyu kumar vatsa.";
            char[] arr1 = new char[] { '\t'','' ''.' };
 
            str1 = str1.TrimStart(arr1);
            Console.WriteLine(str1);
 
            Console.ReadKey();
        }
    }
}
 
Above code will produce the following output:
 
image010.jpg
 
TrimEnd() Method
 
Programmers have a common requirement to remove all trailing punctuations from a string and for this C# provides the TrimEnd() method.
 
Let's look at a program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Using TrimEnd()
            string[] str1 = new string[] { "Isn't this so baby?...""I'm not sure.." };
            foreach (string item in str1)  //before trimend
            {
                Console.WriteLine(item);
            }
 
            foreach (string item in str1)  //after trimend
            {
                string trimmed = item.TrimEnd('?''.');
                Console.WriteLine(trimmed);
            }
 
            //Using Custom method for trimend
            string str2 = "Isn't this so baby?...";
            Console.WriteLine(str2); //before custom method call
            string cusTrimmed = cusTrimEnd(str2);
            Console.WriteLine(cusTrimmed);  //after custom method call
 
            Console.ReadKey();
        }
 
        //Custom trimming
        static string cusTrimEnd(string getStr)
        {
            int removeLen = 0;
            for (int i = getStr.Length - 1; i >= 0; i--)
            {
                char let = getStr[i];
                if (let == '?' || let == '.')
                {
                    removeLen++;
                }
                else
                {
                    break;
                }
            }
            if (removeLen > 0)
            {
                return getStr.Substring(0, getStr.Length - removeLen);
            }
            return getStr;
        }
    }
}
 
The above code will produce the following output:
 
image012.jpg
 
Substring() Method
 
Programmers sometimes need to extract a word (set of characters) from a string. For that C# has the Substring() method which will take some values as parameters and displys the result.
 
Syntax: Substring(start_point, number_of_chars)
 
Let's look at a program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //Simple use
            string str1 = "abhimanyu kumar vatsa";
            string subStr1 = str1.Substring(0, 9);
            Console.WriteLine("Sub Name: {0}", subStr1);
 
            //Using with one parameter
            string str2 = "abhimanyu kumar vatsa";
            string subStr2 = str2.Substring(10);  //no 2nd parameter will display from 10 to end, it has only start parameter
            Console.WriteLine("Sub Name: {0}", subStr2);
 
            //Finding middle string
            string str3 = "abhimanyu kumar vatsa";
            string subStr3 = str3.Substring(10, 5);
            Console.WriteLine("Sub Name: {0}", subStr3);
 
            Console.ReadKey();
        }
    }
}
 
Above code will produce the following output:
 
image014.jpg
 
ToCharArray() Method
 
Programmers sometimes require an array buffer from a string, C# has ToCharArray() method that will do this. The ToCharArray() method returns a new char[] array, which can be used like a normal array.
 
Let's look at a program and its output to understand better.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //String to Array, using method
            string str1 = "Abhimanyu Kumar Vatsa";
            char[] toChArray = str1.ToCharArray();
            for (int i = 0; i < toChArray.Length; i++)
            {
                char letter = toChArray[i];
                Console.WriteLine(letter);
            }
 
            //Array to String, using custom method
            string str2="";
            for (int i = 0; i < toChArray.Length; i++)
            {
                str2 += toChArray[i];
            }
            Console.WriteLine(str2);
 
            Console.ReadKey();
        }
    }
}
 
Above code will produce the following output:
 
image016.jpg
 
That's all about the some of the most frequently used string methods. I hope you will find this notes useful. Please place all your questions in the forum section, as there are many members that are always active.
 
Thank you for reading. Keep Commenting.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System

Lambda two tables and three tables inner join code samples