C#

C# String

The objective of this article is to familiarize you with the C# string, given the fact that string manipulation is the most important feature in any programming language.

You will learn

What Is a C# String?

C# string type represents a series of Unicode characters, and it is used to store the text which is one of the most common types of data for variables. The way you tell C# that you are making a string is to put double quotes around the hardcoded text (also called string literal). If you try to enclose a string in single quotes, the compiler takes the value as a char and generates runtime error.

To declare and initialize a string variable, you need to use string keyword, which under the hood translated to the System.String class from .NET Framework. In other words, string is simply an alias for the class System.String.

string strA = "Pirzada";

Where strA is the name of the string variable and "Pirzada" is the predefined textual content assigned to it. This creates a string object that contains "Pirzada".

Basically, the text "Pirzada" is treated internally as a sequential read-only array of Char objects (char[]) with an indexer. The representation of the string content looks closely like this:

Note: String indexing starts with 0 so the index of the first character is 0, 1 is the index of the second character, and so on.

You can extract individual characters from a string, as you would normally do in an array using an indexer-like ([ ]) syntax:

char singleChar = strA[1];
Console.WriteLine(singleChar); // Prints i

Run Demo

However, you can’t change the characters, like this:

strA[1] = 'a';

This would cause a compilation error with the message ”Property or indexer 'string.this[int]' cannot be assigned to -- it is read only” because strings are immutable.

Run Demo

The for and foreach loop can be used to access each character in the string.

string strA = "Pirzada";

// for loop
for(int i = 0; i < strA.Length; i++)
    Console.Write(strA[i] + "  "); // Prints horizontally

// foreach loop
foreach(char c in strA)
    Console.Write(c + "  "); // Prints horizontally

Run Demo

OUTPUT

P i r z a d a

Characteristics of String Class in C#

  • Immutable
  • Reference type
  • Can contain null
  • Overloads the == operator

string vs String

Technically, there is no difference. The string is a built-in alias for System.String.
As far as coding conventions, It’s recommended to use string when declaring a string object, but for string methods use class like String..

string stringObject = "Pirzada";
string stringMethod = String.Concat(strA, strB);

Strings Are Immutable in C#

C# strings are immutable, meaning the contents of a string object cannot be changed once the object is created, which is one of the interesting aspects of System.String class. What is happening behind the scenes, compiler actually creates a new string object each time to hold the new sequence of characters when assigned.
Note: C# string is a reference type.

Consider the following code:

string strA = "Pirzada Rashid";

First, declared and initialized strA with the value "Pirzada Rashid". This allocates a new string object on the heap (managed heap).

string strB = strA;

strB is initialized with a new reference that points to the same string in memory, so strB also contains the value "Pirzada Rashid".

Let’s print the values of strA and strB.

Console.WriteLine($"strA : {strA}");
Console.WriteLine($"strB : {strB}");

strA = strA.Remove(7);

Remove method returns a new object with the value "Pirzada", which is assigned to the strA variable.

Please note that Remove method does not change the existing string but returns a new string as a result. If you try to delete characters without storing them in a variable, the changes would be lost.

Again, print the values of strA and strB.

Console.WriteLine($"strA : {strA}"); // value changed
Console.WriteLine($"strB : {strB}"); // value still same

Changing the value of strA has no effect on strB, which differs from the usual behavior for reference types. Why is that?

Since Strings are immutable, when you change the value of strA, instead of replacing the original value, an entirely new object with new reference is allocated on the heap for the new value "Pirzada" and the old reference is discarded. The strB variable still points to the original object, so its value is unchanged in the process. This is how the system implements immutable.

Run Demo

OUTPUT

strA : Pirzada Rashid
strB : Pirzada Rashid
 
strA : Pirzada
strB : Pirzada Rashid

C# Null String

Technically, a null indicates that the declared string has not been initialized with a valid value, meaning no object is currently associated with the variable.

The null value identified with the null keyword, indicates that a variable is set to nothing.

string strA = null;

To test whether a string is null or not, use the condition

if (strA == null); // true

Attempting to call methods or properties on strA throws a NullReferenceException.

Console.WriteLine(strA.Length);

Run Demo

C# Empty String

An empty string is a string with no characters, meaning zero-length string.

You can initialize a string variable to an empty string, like this:

string strA = "";
// or
string strA = String.Empty;

Recommended way to initialize string is to use String.Empty value, which is same as (” “). From the readability, this sort of code is much more straightforward and less prone to misinterpretation.

Console.WriteLine(strA.Length); // Prints 0

Run Demo

String.Empty is a static read-only field, while ” “ (quote-quote) is a compile time constant that creates a new empty string object on the heap with empty content.

string strA; // Un-initialized - value null;  
string strA = null; // Initialized with null
string strA = "";  // empty string
string strA = string.Empty; // empty string

Strings and Equality

I have initialized two string variables, strA and strB.

string strA = "developer";
string strB = "developer";

Equals() and String.Equals()

Most of the time, when comparing two String objects, you want to determine whether two objects have the same character sequence or not. In this case, you need to use the String class .Equals() method to properly compare two strings for equality.

bool strC = strA.Equals(strB);  
// OR
bool strC = strB.Equals(strA); 

Console.WriteLine(strC); // Prints: True

Note: Equality test is case-sensitive.

.Equals is a convenient instance method, which compares two strings strA & strB to see if they contain the same content and returns the Boolean result of true if the value of strA is the same as the value of strB; otherwise, false.

You can use static String.Equals method to check whether strA & strB are equal, which returns Boolean value of True/False as a result.

bool strC = String.Equals(strA,strB); 
Console.WriteLine(strC); // Prints: True

Run Demo

If first string is null and you try to invoke .Equals() method on it, an exception of type NullReferenceException is thrown with the message 'Object reference not set to an instance of an object'.

string strA = null;
string strB = "developer";

Console.WriteLine(strA.Equals(strB)); // Throws Exception

Instead, use static String.Equals method or == operator for comparing Strings because both are null-safe.

Console.WriteLine(String.Equals(strA, strB)); // No Exception
Console.WriteLine(strA==strB); // No Exception

Run Demo

If you have to compare two strings, ignoring case considerations (uppercase / lowercase), then you could use .Equals() method with the parameter StringComparison.CurrentCultureIgnoreCase.

Let’s compare "developer" with "Developer" with capital D, result would be true:

string strA = "developer";
string strB = "Developer";

Console.WriteLine(strA.Equals(strB, StringComparison.CurrentCultureIgnoreCase)); // True

However, without the StringComparison.CurrentCultureIgnoreCase parameter, the method will return false as a result.

Console.WriteLine(strA.Equals(strB)); // False

Run Demo

string equals vs == Operator

When the == operator is used, you actually use overloaded version of the operator at compile-time to compare the value of two strings. In C#, there is no difference between == operator and .Equals() method as long as both are of type string except the possibility of calling .Equals() on a null which throws NullReferenceException. You can see operator overload implementation here.

Console.WriteLine(strA==strB); // Prints: True

Note: == operator calls String.Equals() method, when both sides of the operator are string expressions.

By default, the == operator tests for reference equality to see if two variables are pointing to the same object in computer’s memory. This behavior is for reference types where == has no overload and the default implementation is used by the framework. Consider the following example:

object objA = "Codebuns";
object objB = objA;    
object objC = new String(new char[] { 'C', 'o', 'd', 'e', 'b', 'u', 'n', 's' });

Console.WriteLine(objA == objC); // Different reference: False
Console.WriteLine(objA == objB); // Same reference: True
Console.WriteLine(objA.Equals(objC)); // Same Value: True

Note: objA & objC refer to two different string objects, but both contain the same value.

In the above code, the == operator is invoked on type object, which compares object references by default. This comparison returns False because both variables refer to the two different objects. On the other hand, Equals will return True because it actually compares the value and both the variables despite different references have the same value.

Run Demo

C# String Concatenation (kon-kat-en-ay-shun)

I have already discussed these topics in detail. Please click on the links below to read more.

The Old Way
String.Concat( ) and “+”
String.Join( )
String.Format( )

The New Way
String Interpolation

C# String Methods and Properties

C# string class provides a lot of useful methods and properties to manipulate strings. Some of the most commonly used are listed below.

C# String Properties

Property Description
Length C# string length property returns the number of characters in the current String.
[index] Indexer returns the character at the specified position.

C# String Methods

Method Description
Compare() C# compare method compares two string objects.
Equals() C# equals method returns Boolean value after comparing two strings.
Contains() C# contains method checks and returns a Boolean value if specified character or string exists in the current string.
StartsWith() C# StartsWith method determines whether the beginning of the current string matches the specified string.
EndsWith() C# EndsWith method determines whether the end of the current string matches the specified string.
Substring() C# Substring method retrieves a substring from a string.
IndexOf() C# IndexOf method returns the index of the first occurrence of a specified string within the current string.
LastIndexOf() C# LastIndexOf method returns the index of the last occurrence of a specified string within the current string.
Insert() C# Insert method returns a new string with a substring inserted at a specified index in the current string.
Remove() C# Remove method removes the specified number of characters from a string.
Concat() C# Concat method concatenates two string objects together.
Join() C# Join method joins an array of strings together with the specified separator between each element.
Replace() C# Replace method replaces all occurrences of the character in the current string with a different character.
Split() C# Split method splits a string into substrings based on the supplied value.
ToLower() C# ToLower method converts and returns a lowercase string.
ToUpper() C# ToUpper method converts and returns an uppercase string.
Trim() C# Trim method removes all the whitespace or a set of specified characters from the beginning and end of the current string.
TrimStart() C# TrimStart method removes all the whitespace or a set of specified characters from the beginning of the current string.
TrimEnd() C# TrimEnd method removes all the whitespace or a set of specified characters from the end of the current string.
ToCharArray() C# ToCharArray method converts a string into an array of character.
IsNullOrEmpty() C# IsNullOrEmpty method checks whether a string variable is null or an empty string (“”).
IsNullOrWhitespace() C# IsNullOrWhitespace method checks whether a string variable is null, empty, or consists only of white-space characters.

C# String Code Examples

Let’s look at the examples.

Length

C# string Length is the read-only property which returns the total number of characters in the current string. You cannot change the length of a string because it is immutable.

string strA = "Hi, Pirzada";
Console.WriteLine(strA.Length); // 11

Run Demo

Compare()

C# string Compare method compares two specified String objects in lexicographical order and returns an integer that indicates their relative position in the sort order.

String.Compare returns an integer value, which can be equal to zero, greater than zero or less than zero.

  • 0 if same position.
  • +1 if strA follows strB.
  • -1 if strA precedes strB.

According to MSDN
Use the String.Compare method to sort strings, not to check for equality.

string strA = "Pirzada";
string strB = "pirzada";

1 – Method Signature: int Compare(string strA, string strB);

int order = String.Compare(strA, strB);

switch(order) { 
    case 0: 
        Console.WriteLine($"{strA} and {strB} have the same position."); 
        break; 
    case +1: 
        Console.WriteLine($"{strA} follows {strB}.");
        break; 
    case -1: 
        Console.WriteLine($"{strB} precedes {strA}.");  
        break; 
}
OUTPUT

Pirzada follows pirzada.

2 – Method Signature: int Compare (string strA, string strB, bool ignoreCase);

The third parameter ignoreCase is optional, which is always set to “True” to ignore case-sensitive match. Use “False” to enable case-sensitive comparison.

int order = String.Compare(strA, strB, true);

switch(order) { 
    case 0: 
        Console.WriteLine($"{strA} and {strB} have the same position."); 
        break; 
    case +1: 
        Console.WriteLine($"{strA} follows {strB}.");
        break; 
    case -1: 
        Console.WriteLine($"{strB} precedes {strA}.");  
        break; 
}
OUTPUT

Pirzada and pirzada have the same position.

Run Demo

Equals()

C# string Equals method is used to test whether two strings are equal and returns true if the strings are identical, false otherwise.

string strA = "Pirzada";
string strB = "Hello Codebuns.com";

1 – Method Signature: bool Equals(string value);

Console.WriteLine(strA.Equals(strB)); // false
Console.WriteLine(strA.Equals(strA)); // true

Note: Throws NullReferenceException if strA is null.

2 – Method Signature: bool Equals(string a, string b);

Console.WriteLine(String.Equals(strA, strB)); // false
Console.WriteLine(String.Equals(strA, strA)); // true

strA and strB can be string variables or string literals, like this.

"Pirzada".Equals(strA); // true

Run Demo

Contains()

C# string Contains method returns a Boolean true/false indicating whether a specified substring exists within the current string.

Method Signature: bool Contains(string value);

string strB = "Hello, Codebuns.com";
Console.WriteLine(strB.Contains("Codebuns")); // true
Console.WriteLine(strB.Contains("Hmm")); // false

Run Demo

StartsWith()

C# string StartsWith method determines whether the beginning of the current string instance matches a specified string.

Method Signature: bool StartsWith(string value);

string strA = "Pirzada";
Console.WriteLine(strA.StartsWith("Pi")); // true
Console.WriteLine(strA.StartsWith("da")); // false

Run Demo

EndsWith()

C# string EndsWith method determines whether the end of a current string instance matches a specified string.

Method Signature: bool EndsWith(string value);

string strA = "Pirzada";
Console.WriteLine(strA.EndsWith("da")); // true
Console.WriteLine(strA.EndsWith("Pi")); // false

Run Demo

Substring()

C# string Substring method extracts part of a string, called substring from a longer string. There are two overloads for this method.

string strB = "Hello Codebuns.com";

1 – Method Signature: string Substring(int startIndex);

Red is the index of the starting position, where the substring starts. By default, it substrings all remaining characters.

Console.WriteLine(strB.Substring(6));
OUTPUT

Codebuns.com

2 – Method Signature: string Substring (int startIndex, int length);
The first argument specifies the index of the starting position to extract followed by the length (number of characters to extract).

Console.WriteLine(strB.Substring(6, 8));
OUTPUT

Codebuns

Run Demo

IndexOf()

C# string IndexOf method searches for a specified string within another string, returning the position of the found string with a numeric index value. The method returns -1 if the character or string not found.

string strB = "Hello Codebuns.com";

1 – Method Signature: int IndexOf(char value);

Console.WriteLine(strB.IndexOf('b')); // 10

2 – Method Signature: int IndexOf(string value);

Console.WriteLine(strB.IndexOf("com")); // 15

3 – Method Signature: int IndexOf(char value, int startIndex);
The first parameter is the ‘search string’ you are searching for and the second is the numeric position where you want to begin the search.

Red indicates the starting position of search within the current string, forward.

Console.WriteLine(strB.IndexOf('C', 1)); // 6
Console.WriteLine(strB.IndexOf('C', 10)); // -1

4 – Method Signature: int IndexOf(string value, int startIndex);

Console.WriteLine(strB.IndexOf("Code", 3)); // 6

Run Demo

OUTPUT

10
15
6
-1
6

LastIndexOf()

C# string LastIndexOf method returns the index position of the last occurrence of a particular character/substring within the target string. Method returns -1 if the character or string not found.

string strB = "Hello Codebuns.com";

1 – Method Signature: int LastIndexOf(string value);

Searches from the end towards the beginning.

Console.WriteLine(strB.LastIndexOf(".com")); // 14

2 – Method Signature: int LastIndexOf(char value);

Console.WriteLine(strB.LastIndexOf('o')); // 16

3 – Method Signature: int LastIndexOf (char value, int startIndex);

Red indicates the starting position of search towards the beginning within the string.

Console.WriteLine(strB.LastIndexOf('e', 14)); // 9

4 – Method Signature: int LastIndexOf(string value, int startIndex);

Console.WriteLine(strB.LastIndexOf("Code", 12)); // 6

Run Demo

OUTPUT

14
16
9
6

IndexOf() vs LastIndexOf()

The only difference between these methods is the search direction. Let us take a very simple example.

string strB = "Hello Codebuns.com";

indexOf()
Search starts from the first index 0 towards the last index 17 and returns the specified character/substring within the provided string.

The first occurrence of o found at the index 4.

Console.WriteLine(strB.IndexOf('o')); // 4

LastIndexOf()
Search starts from the last index 17 towards the first index 0 and returns the specified character/substring within the provided string.

The first occurrence of o found at the index 16, because of the opposite search direction. The last occurrence, if you take the search from the first index 0 to the last index 17.

Console.WriteLine(strB.LastIndexOf('o')); // 16

Run Demo

Insert()

C# string Insert method returns a new string in which a provided string is inserted at a specified index position in the current string.

Method Signature: string Insert (int startIndex, string value);

string strA = "Pirzada";
Console.WriteLine(strA.Insert(0, "Hi, "));

Run Demo

OUTPUT

Hi, Pirzada

Remove()

C# string Remove method returns a new string in which a specified number of characters from the current string are deleted.

string strB = "Hello Codebuns.com";

1 – Method Signature: string Remove (int startIndex);

Red indicates the index of the starting position, from where all the characters will be removed from the string.

Console.WriteLine(strB.Remove(5));
OUTPUT

Hello

2 – Method Signature: string Remove (int startIndex, int count);

The first parameter is the index of the starting position followed by the number of characters to remove from the string.

Console.WriteLine(strB.Remove(5, 9));
OUTPUT

Hello.com

Run Demo

Concat()

C# string Concat is the static method which concatenates one or more instances of String.

Method Signature: string Concat (string str0, string str1);

string strA = "Pirzada";
string strC = "Hello ";

Console.WriteLine(String.Concat(strC, strA));
Console.WriteLine(String.Concat(strC, "Codebuns.com"));

Run Demo

OUTPUT

Hello Pirzada
Hello Codebuns.com

Join()

C# string Join method concatenates the elements of an array, using the specified separator between each element.

string[] strArray = {"111","222","3333"};

1 – Method Signature: string Join (string separator, string[] value, int startIndex, int count);

Console.WriteLine(String.Join("|", strArray, 0, 2));
Console.WriteLine(String.Join("/", strArray, 1, 2));
OUTPUT

111|222
222/3333

2 – Method Signature: string Join (string separator, params string[] value);

Console.WriteLine(String.Join("-", strArray));
OUTPUT

111-222-3333

Run Demo

Replace()

C# string Replace method searches and replaces any string with another string. Search is case-sensitive and must match exactly.

string strC = "111-222-3333";

1 – Method Signature: string Replace (string oldValue, string newValue);

OUTPUT

444-222-3333

Console.WriteLine(strC.Replace("111", "444"));

2 – Method Signature: string Replace (char oldChar, char newChar);

Console.WriteLine(strC.Replace('-', '/'));
OUTPUT

111/222/3333

Run Demo

Split()

C# string Split method returns an array of string that contains the substrings after splitting the source string at the specified points.

string strC = "111-222-3333";

Method Signature: string[] Split (params char[] separator);

The following code obtains the array of substrings by splitting the strC variable value at each — character.

string[] strArray = strC.Split('-');

Next, you loop through the array using foreach and prints out all the array elements to the console:

foreach (string str in strArray)
	Console.WriteLine(str);

Run Demo

OUTPUT

111
222
3333

Splitting String by Multiple Separators
The following code splits the content of a string into the array of substrings using multiple delimiting characters passed as an argument of the method.

string strA = "1,2/3#4,5,6";

char[] separators = new char[] {',', '/', '#' };
string[] strArray = strA.Split(separators);

foreach (string str in strArray)
    Console.Write(str); // Prints horizontally

Run Demo

OUTPUT

123456

ToUpper()

C# string ToUpper method returns a copy of the current string converted to uppercase.

Method Signature: string ToUpper();

string strA = "Pirzada";
Console.WriteLine(strA.ToUpper());

Run Demo

OUTPUT

PIRZADA

ToLower()

C# string ToLower method returns a copy of the current string converted to lowercase.

Method Signature: string ToLower();

string strA = "Pirzada";
Console.WriteLine(strA.ToLower());

Run Demo

OUTPUT

pirzada

Trim()

C# string Trim method gets rid of both the leading and trailing spaces from a text string.

string strD = "  C# Programming  ";

Method Signature: string Trim();

Console.WriteLine(strD.Trim());

Run Demo

OUTPUT

C# Programming

TrimStart()

C# string TrimStart method gets rid of the leading spaces, but not the trailing spaces from a text string.

string strD = "  C# Programming  ";

Method Signature: string TrimStart();

Console.WriteLine(strD.TrimStart());

Run Demo

OUTPUT

C# Programming

TrimEnd()

C# string TrimEnd method gets rid of the trailing spaces, but not the leading spaces from a text string.

string strD = "  C# Programming  ";

Method Signature: string TrimEnd();

Console.WriteLine(strD.TrimEnd());

Run Demo

OUTPUT

C# Programming

ToCharArray()

C# string ToCharArray method returns an array of Unicode character after converting the provided string.

string strA = "Hi, Pirzada";

1 – Method Signature: char[] ToCharArray();

char[] charArray = strA.ToCharArray(); // Convert String to Char Array
foreach (char ch in charArray)  
	Console.WriteLine(ch);
OUTPUT

H
i
,
 
P
i
r
z
a
d
a

2 – Method Signature: char[] ToCharArray(int startIndex, int length);

Red indicates the index of the starting position followed by a length (number of characters to extract).

char[] charArray = strA.ToCharArray(4, 5);
foreach (char ch in charArray)  
	Console.WriteLine(ch);
OUTPUT

P
i
r
z
a

Run Demo

String.IsNullOrEmpty()

Starting with C# version 2005, Microsoft introduced a Boolean string method IsNullOrEmpty() to test whether the value of a string is blank, empty, or null.

IsNullOrEmpty() is equivalent to: s == null || s == String.Empty;

Let’s look at the example.

string strA = null;
string strB = String.Empty;
string strC = "Pirzada";
string strD = "";

Console.WriteLine(check(strA)); // True
Console.WriteLine(check(strB)); // True
Console.WriteLine(check(strC)); // False
Console.WriteLine(check(strD)); // True

public static bool check(string str) 
{ 
     return String.IsNullOrEmpty(str);
}

Run Demo

String.IsNullOrWhitespace()

C# string IsNullOrWhitespace method checks whether a specified string is null, empty, or consists only of white-space characters.

IsNullOrWhiteSpace() is equivalent to: String.IsNullOrEmpty(value) || value.Trim().Length == 0;

Method Signature: bool IsNullOrWhiteSpace(string value);

Let’s look at the example.

string strA = null;
string strB = String.Empty;
string strC = "Pirzada";
string strD = "";
string strE = "\t";
string strF = " \n ";

Console.WriteLine(check(strA)); // True
Console.WriteLine(check(strB)); // True
Console.WriteLine(check(strC)); // False
Console.WriteLine(check(strD)); // True
Console.WriteLine(check(strE)); // True
Console.WriteLine(check(strF)); // True

public static bool check(string str) 
{ 
     return String.IsNullOrWhiteSpace(str);
}

Run Demo

ToString( )

C# ToString method converts the value of an object to a regular string (returns string representation).

Method Signature: string ToString();

int number = 22;  
string strNumber = number; // Error: Cannot implicitly convert type 'int' to 'string'

// Number converted to type String
string strNumber = number.ToString();

Console.WriteLine("Number -> " + strNumber); // Number -> 22

Run Demo

Useful Articles

C# Reference | Microsoft Docs

Sending
User Rating 5 (1 vote)
Tagged in :

Add Comment

Click here to post a comment

Send this to a friend