16 - Strings in C#

16.1 Creating string in C#

A string is an object of type String that stores the value in the form of a text. The text is stored as a sequence of read only characters stored in an array. The string in C# contains embedded null characters (‘\O’). The string keyword in C# is an alias for String. The String class provides various string operations as creating, manipulating, concatenating and comparing the values.

String objects can be created by any of the following methods as mentioned below:

a) Assigning a string literal to a String variable

string name;
name = “Jennifer”;

Console.WriteLine( “The name is:”+name );

The string literal is assigned to the name variable of type string.

b) Using the string concatenation

string name, level;
name = “Jennifer”;

level = “MBA”;

string value = name + level;
Console.WriteLine( “The detail is:”+name +level );
Console.Read();

The value variable contains the concatenation of two strings as name and level respectively.

c) Using the String class constructor

static void Main) string[ ] args )
{
    char[ ] location = new char [7] { ‘N’, ‘e’, ‘w’, ‘Y’, ‘o’, ’r’ ,’k’};
     string address1 = new string(location);
    Console.WriteLine(address1);
    Console.Read();
}

The location array contains the elements of char type. The variable of type string is used to display values.

d) Retrieving property or calling a method that returns a string

string[ ] data = new string[] {“Learn”, “Strings”, “In”, “C#”};
string output = String.Join (“ “, data);
Console.WriteLine(output);

Console.Read();

The Join method is used for combining the values in the string array.

e) The method used for formatting or converting the value to specific string representation

DateTime d = new DataTime (2014, 10, 1, 10, 30, 15);
string values = String.Format(“Message sent on {0:t} on {0:D}”, d);
Console.WriteLibe(“The value is:{0}”, values);

Console.Read();

The Date and Time when the user communicated is displayed using the DateTime method of C#.

16.2 Properties of string class

The String type has two properties as mentioned below:

Type

Description

Chars

It gets the Char object at a specified position in the current String object

Length

It gets the number of characters in the current String object

A code sample to demonstrate the properties in C# is as shown below:

class Program
{
    static void Main( string[ ] args )
    {
        string str1 = “Welcome”;
        for ( int c=0; c<str1.Length-1; c++);
    {
        Console.WriteLine(“{0}”, str1[c]);
    }
        Console.WriteLine(“The length of the string ‘{0}’ is {1}”, str1, str1.Length);
        Console.Read();
    }
}

The output for the code is as shown below:

16.3 Methods of string class

Some of the methods of the string class are as shown below:

Method

Description

Clone()

It is used to make the clone of the string

Compare()

It compares the two specified strings and returns the integer value

Concat()

It is used for concatenation of two string objects

Contains()

It is checks whether the specified character or string exists in the string value

Copy()

It creates a new string object with the same value as the specified string

EndsWith()

It is used to check whether the specified character is the last character of the string

Equals()

It compares two strings and returns the Boolean value as output

GetHashCode()

It returns the HashValue of the specified string

GetType()

It returns the System.Type of the current instance

IndexOf()

It returns the index position of the first occurrence of the specified character

ToLower()

It converts the string into lower case

ToUpper()

It converts the string into upper case

Insert()

It inserts the string or character in the string at a specific position

LastIndexOf()

It returns the index position of last occurrence of the specified character

Remove()

It is used to delete all the characters from the beginning to the specific position

Replace()

It is used to replace a character in the string

Split()

It splits the string based on the specific value

StartsWith()

It checks the first character of the string matches with the specific character

Substring()

It is used to return the substring

ToCharArray()

It converts the string to the character array

Trim()

It removes the extra whitespaces from the beginning and the end of the string

 

class Program
{
    static void Main ( string[ ] args )
    {
        string city;
        city = “London”;
        string country;
        country = “United Kingdom”;

        Console.WriteLine(city.Clone());
        //The clone of the string is created

        Console.WriteLine(city.CompareTo(country));
        //It compares the two strings and returns 0 if True else 1 for false  
  
        Console.WriteLine(country.EndsWith(“m”));
        //It checks whether the specified character is the last character

        Console.WriteLine(country.Contains(“King”));
        //It checks whether the value specified is present in the string

        Console.WriteLine(city.Equals(country));
        //It compares the two strings and returns to true or false

        Console.WriteLine(city.CompareTo(country));
        //It is used for the comparison of two strings

        Console.WriteLine(country.GetHashCode());
        //It is used for returning the Hash code for the string

        Console.WriteLine(country.ToLower());
        //It converts the string to Lower case

        Console.WriteLine(city.ToUpper());
        //It converts the string to upper case  
  
        Console.WriteLine(country.Insert ( 0, “A”));
        //Inserts the value at the specified position

        Console.WriteLine(city.LastIndexOf(“n”));
        //Returns the last index value of the specified value

        Console.WriteLine(country.Remove(6));
        //Removes the character from the specified position

        Console.WriteLine(city.StartsWith(“L”));
        //Returns the first character of the string with the specified value

        Console.WriteLine(country.Substring(3,4));
        //Returns the substring of the specified string

        Console.WriteLine(country.Trim());
        //removes the starting and ending whitespaces in the string

        string[ ] split = city.Split(new char[] {“0”});        
        Console.WriteLine(split[0]);
        Console.WriteLine(split[2]);
        Console.Read();
    }
}

Sample code for demonstrating the methods of string class in C# is as shown below:

The output for the code is as shown below:

16.4 Example of string in C#

class Program
{
    static void Main ( string[ ] args )
    {
        string s1 = “Strings are literals”;
        string s2 = “Values are assigned to the variables”;
        s1 = s1 + s2;
        Console.WriteLine(s1);

        string s3 = “Reverse letters”;
        for ( int i=0; i<14; i++)
        {
            Console.WriteLine(s3[ s3.Length – i – 1] );
        }
        string [ ] data = { “C# data”, “Array data”, “collection of data”};
        string pattern = “data”;
    
        foreach ( string s in data )
        {
            Console.Write(“{0,9}”, s);
            if ( System.Text.RegularExpression.Regex.IsMatch ( s, pattern , System.Text.RegularExpressions.RegexOptions.IgnoreCase) );
            {
                Console.WriteLine((“match for {0} found), pattern );
            }
            else
            {
                Console.WriteLine();
            }
        }
    }
    Console.Read();
}

A sample code to demonstrate the string functionality in C# is as shown below:

The output for the code is as shown below:

In the above code, the concatenation, reverse of string and identifying values through regular expressions is performed on different string variables. The output received after applying various functions is as shown above.

Like us on Facebook