C# String Functions

We already know the string is a reference type. C# provides us with 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 is 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., the 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 the console.

Next for demonstrating on property Chars(int32), we have written for loop in which integer variable i 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 a 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 splits the string into substrings based on the characters in the array.
str1 = “Hello_this_is_tutorial_on_C#” String[] s = str1.Split(“_”)
Split(char[])This C# string function retrieves a substring starting from the position specified until the last position of the current instance.
str.Substring(1)
Substring(int32)It will return a new string by deleting all the characters starting from the position specified until the last position from the current one.
str.Remove(5);
Remove(int32)It returns an integer that indicates the position in sort order when two string objects are compared.
String.Compare(str, str1)
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 one.
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()This C# String Function 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()This C# String Function returns a new string by deleting all the leading and trailing whitespaces from the current instance.
Str.Trim()
Contains(String)It returns a Boolean value which indicates whether the 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());
       }
}
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 “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);
   }
}
ToLower, SubString, and Split Examples

ANALYSIS

Str1 = “Hello”;

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

str1.Substring(1) outputs all the elements in the 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 text value present in string object st based on the text passed as an argument to the split method and store the new string in the array sep[].

i.e., The “Welcome-to-C#” is separated based on the “-“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));
      }
}
Replace, Remove, and Join Examples 4

ANALYSIS

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 elements in str1, i.e., Hello starting from index position three till the end, which results in it.

Hel

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

H a i

C# IsNullOrEmpty, Copy, and Insert string function 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));
    }
}
C# String Functions 5

ANALYSIS

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

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

str1.Insert(1, str2) inserts the 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();
  }
  }
C# String Functions 6

ANALYSIS

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

System.String[]

Compare(str1, str2) – The C# Compare function 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.

Concat(str1, str2) will concat both of them, 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);
  } 
}
C# String Functions 7

ANALYSIS

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

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

str.Contains(“is a”) checks whether the text 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.

Categories C#