Strings in C#: Part 1


Introduction

 

The uncapitalized "string" is an alias type of the System.String class; this class provides a set of methods to work on strings. Let's list some of them that we will cover in this article.

 

Method

Meanings

ToUpper()

ToLower()

ToTitleCase()

Creates a copy of a given string in upper case or lower case or in title case.

Length()

Returns the length of the string.

Concat()

Returns a new string that is composed of two discrete strings.

Contains()

Determine if the current string object contains a specified string.

Compare()

CompareTo()

CompareOrdinal()

Compares two strings.

Copy()

Returns a fresh new copy of an existing string.

Format()

Formats string literal using other primitives like numerical data and other strings and the {0} notation we uses.

Insert()

Receives a copy of the current string that contains newly inserted string data.

PadLeft()

PadRight()

Returns copies of the current string that has been padded with specific data.

Remove()

Replace()

Receives copy of string with modifications.

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()

TrimStart method removes characters specified in an array of characters from the beginning of a string.

TrimEnd()

TrimEnd method removes characters specified in an array of characters from the end of a 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.

 

ToUpper/ToLower/ToTitleCase Methods

 

These case handling methods are used to convert a copy of a given string in an appropriate case. We need to pay special attention while converting to tile case because ToTitleCase() method is used with System.Globalization class. Remember to use System.Globalization namespace when using any globabization feature.

 

Generally, title casing converts the first character of a word to uppercase and the rest of the characters to lowercase. However, this method does not currently provide proper casing to convert a word that is entirely uppercase, such as an acronym. If you really wish to convert entirely uppercase to title case then, use following special method.

 

Console.WriteLine(myTI.ToTitleCase(txt2.ToLower()));

 

Let's look at program and its output to understand better.

 

The program given below changes the casing of a string based on the English (United States) culture, with the culture name en-US.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Globalization;

 

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            string txt1 = "test this string";

            Console.WriteLine("Using LowerCase and UpperCase without Globalization");

            //Convert string to uppercase

            Console.WriteLine(txt1.ToUpper());

            //Convert string to lowercase

            Console.WriteLine(txt1.ToLower());

 

            string txt2 = "TESt";

            Console.WriteLine("Using LowerCase and UpperCase with Globalization");

            //Creates a TextInfo based on the "en-US" culture.

            TextInfo myTI = new CultureInfo("en-US"false).TextInfo;

            Console.WriteLine(myTI.ToTitleCase(txt2));

            //Use below one for entirely uppder case sentences like "TEST" instead of "TESt"

            Console.WriteLine(myTI.ToTitleCase(txt2.ToLower()));

            Console.WriteLine(myTI.ToUpper(txt2));

            Console.WriteLine(myTI.ToLower(txt2));

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Length() Method
 

Its quite easy to understand. The C# String Length function returns the total number of characters in the specified string. C# length function proves itself as very useful one when it is used with some other C# string functions such as remove, insert etc.

 

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)

        {

            string txt1 = "test this string";

 

            //Simple use

            int count = txt1.Length;

            Console.WriteLine(count);

 

            //Using with another string methods

            Console.WriteLine(txt1.Remove(txt1.Length - 1));

            Console.WriteLine(txt1.Remove(txt1.Length - 2));

            Console.WriteLine(txt1.Remove(txt1.Length - 3));

            Console.WriteLine(txt1.Remove(txt1.Length - 4));

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

 

Concat() Method

 

Concatenate string returns a new string that is composed of two discrete strings. We Concatenate strings with the + operator as well as the same which compiles to the string.Concat method. We can also use string.Concat directly because as internally, the C# compiler converts the plus operator into string.Concat, so only the syntax is different.

 

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)

        {

            //Adding strings using + operator

            string str0 = "String 0";

            string str1 = "String 1";

            string str2 = str0 + " " + str1 + " " + "String 2";

            Console.WriteLine(str2);

 

            //Adding string using += operator

            string str3 = "String 3";

            string str4 = "String 4";

            string str5 = "String 5";

            str3 += " " + str4 + " " + str5;

            Console.WriteLine(str3);

 

            //Adding strings using string.Concat() method

            string str6 = "String 6";

            string str7 = "String 7";

    string str8 = string.Concat(str6, " ", str7, " ", "String 8");

            Console.WriteLine(str8);

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Contains() Method

 

The contains method can be used if you want to check if a string contains certain characters. The Contains method provides a case-sensitive ordinal method for checking string contents. Contains method returns bool result which is true if the parameter is found, and false if it is not found.

 

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 Contains method

            string str1 = "I am Abhimanyu Kumar Vatsa";

            bool result = str1.Contains("Abhimanyu");

            Console.WriteLine(result);

 

            //Using Contains in Array

            string [] str2 = new string[]{"Abhimanyu""Kumar""Vatsa"};

            bool result1 = str2.Contains("Abhimanyu");

            Console.WriteLine(result1);

            bool result2 = str2.Contains("kumar");

            Console.WriteLine(result2);

 

            //Using Contains in List

            var list = new List<string>();

            list.Add("Abhimanyu");

            list.Add("Kumar");

            list.Add("Vatsa");

            if (list.Contains("Abhimanyu")) //try by changing case

            {

                Console.WriteLine("Abhimanyu Found.");

            }

            else

            {

                Console.WriteLine("Abhimanyu Not Found.");

            }

 

            //no matter of case here. try by changing case, will not make difference

            if (list.Contains("Abhimanyu"StringComparer.OrdinalIgnoreCase))

            {

                Console.WriteLine("Abhimanyu Found (using StringComparer).");

            }

 

            //Using Contains method by calling function/method

            findstring(str1);

 

            Console.ReadKey();

        }

 

        static void findstring(string getData)

        {

            bool result3 = getData.Contains("Abhimanyu"); //true

            Console.WriteLine(result3);

            bool result4 = getData.Contains("kumar"); //false because of case

            Console.WriteLine(result4);

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Compare()/CompareTo()/CompareOrdinal() Methods

 

In C#, comparison methods, including Compare, CompareTo and CompareOrdinal provides functionality to determine if one string is ordered before another when in alphabetical order, or whether it is ordered after or is equivalent. If the first string is bigger, the result is 1. If both strings are equal, the result is 0. If the first string is smaller, the result is -1.

 

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)

        {

            string a = "a"// it is 1

            string b = "b"// it is 2

 

            int c = string.Compare(a,b);

            Console.WriteLine("Compare(a,b) : " + c);

 

            int c1 = string.Compare(b, a);

            Console.WriteLine("Compare(b,a) : " + c1);

 

            int c2 = string.CompareOrdinal(b, a);

            Console.WriteLine("CompareOrdinal(b, a) : " + c2);

 

            int c3 = string.CompareOrdinal(a, b);

            Console.WriteLine("CompareOrdinal(a, b) : " + c3);

 

            int c4 = a.CompareTo(b);

            Console.WriteLine("CompareTo(b) : " + c4);

 

            int c5 = b.CompareTo(a);

            Console.WriteLine("CompareTo(a) : " + c5);

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Copy() Method

 

This method is bit simple, it just returns a fresh new copy of an existing string to another string.

 

Let's look at a sample 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 str1 = "sample text";

            string str2 = string.Copy(str1);

 

            Console.WriteLine(str1);

            Console.WriteLine(str2);

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Format() Method

 

Formats string literal using other primitives like numerical data and other strings and the {0} notation we uses. This method uses substitution technique.

 

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)

        {

            string val1 = "Abhimanyu Kumar Vatsa";

            int val2 = 10000;

            DateTime val3 = new DateTime(1988, 06, 06);

            string result = string.Format("{0} || {1:0.0} || {2:yyyy}", val1, val2, val3);

            Console.WriteLine(result);

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Insert() Method

 

Receives a copy of the current string that contains newly inserted string data. Here we see how we can use the string Insert method to place one string in the middle of another one, or at any other position.

 

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 Vatsa";

            string fullname = str1.Insert(10, "Kumar ");

            Console.WriteLine(fullname);

 

            //Using with IndexOf

            string str2 = "Learning C# easy.";

            int index = str2.IndexOf("C# ");  //returns 9

            string fullSen = str2.Insert(index + "C# ".Length, "is ");

            Console.WriteLine(fullSen);

 

            Console.ReadKey();

        }

    }

}

 

The preceding code will produce the following output:

 

Strings in C#
 

Move to next part for more string discussion.

 

Thanks for reading.

 

HAVE A HAPPY CODING!!


Recommended Free Ebook
Similar Articles