C# String Functions

We already know the string is a reference type. C# is providing us a large number of string functions for manipulating strings.

Before we get into the C# string function, let me show you the available properties. The following are the C# string properties:

PropertyDescription
Chars(int32)It returns the char object at the position specified from the current string
LengthIt returns the length of the string (i.e., number of characters in the string object)

C# String Functions Example

Let us see an example demonstrating the properties.

using System;
  class Program
  {
    static void Main(string[] args)
    {
    string str = "Tu4tor8ial";
    Console.WriteLine("Number of characters in the string: " +str.Length);
    for (int i = 0; i < str.Length; i++)
    {
      if (Char.IsLetter(str[i]))
        Console.WriteLine("{0} is a character", str[i]);
      else
        Console.WriteLine("{0} is a digit", str[i]);
    }
    Console.ReadKey();
    }
  }

OUTPUT

C# String Functions 1

ANALYSIS

Declared a string variable str and initialized it with some characters(both letters and digits) “Tu4tor8ial”.

Str.Length will give the number of characters in the string str which is in this example 10 so it prints 10 onto console.

Next for demonstrating on property Chars(int32), we have written for loop in which integer variable I is initialized with zero and gets iterated until I < str.Length returns false.

And for every I value, if the method IsLetter(str[i]) of char returns true, i.e., T is a letter. Hence it returns true so that it prints the statement

 T is a character
 is executed
.

In the same way when i=2, then Char.IsLetter(str[i]) returns false since it is not a letter it is number 4 which is a digit. So it prints statement.

“4 is a digit”

Some of the most commonly used C# string functions are:

string str, str1,str2;  // declared string variables

str = “Tutorial”

str1 = “Welcome”

string[] sarray = {“Hello”, “Hai”};

The following are the list if available C# string functions and their description.

C# String FunctionsDescription
ToUpper()It returns the copy to the current string by converting it to upper case.
Str.ToUpper()
ToLower()It returns the copy to the current string by converting it to lower case.
Str.ToLower()
Insert(int32, String)It returns a new string in which the string specified inserted in the index position specified in the current string instance.
str2 = String.Insert(1, str)
Split(char[])It splits the string into substring based on the characters in the array.
str1 = “Hello_this_is_tutorial_on_C#” String[] s = str1.Split(“_”)
Substring(int32)This C# string function retrieves a substring starting from the position specified untill the last position of the current string instance.
str.Substring(1)
Remove(int32)It will return a new string by deleting all the characters starting from the position specified untill the last position from the current string.
str.Remove(5);
Join(string, string[])It joins all the elements of string[] with the string specified.
String.Join(“,”, sarray[])
Format(String, Object)It replaces one or more format items in the string specified with the string representation of the object specified.
String s = String.Format(string, object)
Copy(String)It creates a new instance of str with the same string value as the specified string.
str1 = String.Copy(str);
Concat(String, String)It concatenates two string instances.  
String.Concat(str, str1)
Compare(String, String)It returns an integer that indicates the position in sort order when two string objects compared.
String.Compare(str, str1)
Clone()It returns a reference to the string instance str.  
str.Clone()
GetType()It gets the type of the current object or instance.
str.Gettype()
IsNullOrEmpty(string)Indicates whether the string specified is null or empty by returning a Boolean value.
String.IsNullOrEmpty(str);
Replace(String, String)It replaces the specified substring of the current instance of the string with the string specified.
String s1 = str.Replace(“Tu”, “Tw”)
ToString()It returns the instance of the current string.
Str.Tostring()
Trim()It returns a new string by deleting all the leading and trailing whitespaces from the current instance of a string.
Str.Trim()
Contains(String)It returns a Boolean value which indicates whether the string str is having the specified substring substr.
bool I = str.Contains(substr);

C# String Functions Trim, ToString, and ToUpper Examples

Let us see an example C# code demonstrating on Trim(), ToString(), ToUpper()

using System;
    class Program
    {
        static void Main(string[] args)
        {
        string str2 = "Hai";
        string[] str = { "H","a","i" };
        string str1 = "Hello";
        string sw = " a b c d ";
        Console.WriteLine("Trim():");
        Console.WriteLine(sw.ToString());
        Console.WriteLine(sw.Trim());
        Console.WriteLine();

        Console.WriteLine("ToString():");
        Console.WriteLine(str1.ToString());
        Console.WriteLine();

        Console.WriteLine("Toupper():");
        Console.WriteLine(str1.ToUpper());
       }
}

OUTPUT

C# String Functions 2

ANALYSIS

ToString() will return the reference value in as in the current instance, i.e., “a b c d”

Sw.Trim() trims the leading and trailing whitespaces from the string “a b c d”. So it removes the whitespace before ‘a’ and prints “a b c d”.

str1.ToString() will return the reference value in as in the current instance, i.e., “Hello”.

str1.ToUpper will convert all the elements in str1 to uppercase and prints “HELLO”.

C# String Functions ToLower, SubString, and Split Examples

Let us see an example C# code demonstrating on ToLower(), SubString(), Split()

using System;
  class Program
  {
    static void Main(string[] args)
    {
    string str2 = "Hai";
    string[] str = { "H","a","i" };
    string str1 = "Hello";
    string sw = " a b c d ";
    Console.WriteLine("ToLower():");
    Console.WriteLine(str1.ToLower());
    Console.WriteLine();

    Console.WriteLine("Substring():");
    Console.WriteLine(str1.Substring(1));
    Console.WriteLine();

    Console.WriteLine("Split():");
    string st = "Welcome-to-C#";
    string[] sep = st.Split("-");
    foreach (string st1 in sep)
    Console.WriteLine(st1);
   }
}

OUTPUT

C# String Functions 3

ANALYSIS

Str1 = “Hello”;

str1.ToLower() converts the string in str1 into lower case and prints “hello”.

str1.Substring(1) outputs all the string elements in the string str1 starting from the index position 1, i.e., from e in Hello, So it prints “ello”.

Here, the statement string[] sep = st.Split(“-“); is saying to split the string value present in string object st based on the string passed as an argument to the split method and store the new string in the string array sep[].

i.e., The string “Welcome-to-C#” is separated based on the string “-“which results in the following output.

Welcome
to
C#

C# String Functions Replace, Remove, and Join Examples

Let us see an example C# string functions code demonstrating on Replace(), Remove(), Join()

using System;
  class Program
  {
    static void Main(string[] args)
    {
    string str2 = "Hai";
    string[] str = { "H","a","i" };
    string str1 = "Hello";
    string sw = " a b c d ";
    Console.WriteLine("Replace():");
    string s1 = str1.Replace("He", "ha");
    Console.WriteLine(s1);
    Console.WriteLine();


    Console.WriteLine("Remove():");
    Console.WriteLine(str1.Remove(3));
    Console.WriteLine();


    Console.WriteLine("Join():");
    Console.WriteLine(String.Join(" ", str));
      }
}

OUTPUT

C# String Functions 4

ANALYSIS

String s1 = str1.Replace(“He”, “ha”)

Represents the new string s1 which is the result of replacing “He” in “Hello” with “Ha” which looks like

“hallo”

str1.Remove(3) results in a new string formed after removing all the string elements in str1, i.e., Hello starting from index position three till the end, which results in the string.

Hel

String.Join(“”, str) joins the elements in the string array in str[] with space(“”) that results in

H a i

C# IsNullOrEmpty, Copy, and Insert Examples

Let us see an example demonstrating the C# string functions IsNullOrEmpty(), Copy(), and Insert().

using System;
  class Program
  {
    static void Main(string[] args)
    {
    string str2 = "Hai";
    string[] str = { "H","a","i" };
    string str1 = "Hello";
    string sw = " a b c d ";
    Console.WriteLine("IsNullOrEmpty():");
    Console.WriteLine(String.IsNullOrEmpty(str1));
    Console.WriteLine();

    Console.WriteLine("Copy():");
    string str3 = String.Copy(str1);
    Console.WriteLine(str3);
    Console.WriteLine();

    Console.WriteLine("Insert():");
    Console.WriteLine(str1.Insert(1, str2));
    }
}

OUTPUT

C# String Functions 5

ANALYSIS

String.IsNullOrEmpty(str1) results false because the string instance str1 is not empty.

String str3 = String.Copy(str1) creates a copy of the string object str1 and stores it in another string object str3 that results in “Hello”.

str1.Insert(1, str2) inserts the string value of str2 in the index position 1 of the string value str1, i.e., HHaiello

C# String Functions GetType, Compare, Concat, and Clone Example

In this example, we are going to demonstrate the C# string functions GetType(), Compare(), Concat(), and Clone() with an example of each.

using System;
  class Program
  {
    static void Main(string[] args)
    {
    string str2 = "Hai";
    string[] str = { "H","a","i" };
    string str1 = "Hello";
    string sw = " a b c d ";
    Console.WriteLine("GetType():");
    Console.WriteLine(str.GetType());
    Console.WriteLine();

    Console.WriteLine("Compare():");
    Console.WriteLine(String.Compare(str1, str2));
    Console.WriteLine();

    Console.WriteLine("Concat():");
    Console.WriteLine(String.Concat(str1, str2));
    Console.WriteLine();

    Console.WriteLine("Clone():");
    Console.WriteLine(str.Clone());
    Console.WriteLine();

    Console.WriteLine("Number of characters in the string: " + str.Length);
    Console.ReadKey();
  }
  }

OUTPUT

C# String Functions 6

ANALYSIS

str.GetType() returns the type of the current instance i.e., str which outputs.

System.String[]

String.Compare(str1, str2)

The C# string function Compare() will give a result based on the following table.

ValueCondition
Less than 0The first substring is followed by the second substring in the sort order
ZeroSubstrings occur in the same position in sort order (or) length is 0
Greater than 0The second substring is followed by the first substring in the sort order

In this scenario, the output is 1.

String.Concat(str1, str2) will concat both the strings, which results in “HelloHai”.

str.Clone() returns reference to str, i.e., System.String[]

C# Format and Contains Example

There are two more C# String functions Format() and Contains(). In this example, we will explain both of them.

using System;
  class Program
  {
  static void Main(string[] args)
  {
    Decimal temp = 25.36M;
    string s = String.Format("The temperature is now {0}°C", temp);
    Console.WriteLine(s);
    Console.WriteLine();


    string str = "This is a Tutorial";
    bool i = str.Contains("is a");
    Console.WriteLine(i);
  } 
}

OUTPUT

C# String Functions 7

ANALYSIS

String.Format(“The temperature is now {0}°C”, temp) inserts the decimal value of the string object temp(25.36) in the string specified and displays it as a single string.

i.e., The temperature is now 25.36°C

str.Contains(“is a”) checks whether the string specified is present in the string object str where str = “This is a Tutorial” and returns Boolean value accordingly. In this scenario, it returns true.