C# String with Examples

In c#, the string is a keyword that is useful to represent a sequential collection of characters called a text, and the string is an object of the System.String type.

 

In c#, we use the string keyword to create string variables to hold the particular text, which is a sequential collection of characters.

 

The string variables in c# can hold any kind of text, and by using the Length property, we can know that the number of characters the string variable is holding based on our requirements.

C# String Declaration and Initialization

The following are the different ways of declaring and initializing string variables using string keyword in the c# programming language.

 

// Declare without initializing.
string str1;
// Declaring and Initializing
string str2 = "Welcome to Tutlane";
String str3 = "Hello World!";
// Initialize an empty string.
string str4 = String.Empty;
// Initialize to null.
String str5 = null;
// Creating a string from char
char[] letters = { 'A', 'B', 'C' };
string str6 = new string(letters);

If you observe the above code snippet, we created string variables using string and String keywords with or without initializing values based on our requirements.

C# string vs. String

If you observe the above declarations, we used two keywords called string and String to declare string variables. In c#, the string keyword is just an alias for String, so both string and String are equivalent, and you can use whichever naming convention you prefer to define string variables.

C# String Immutability

In c#, the string is immutable, which means the string object cannot be modified once it is created. If any changes are made to the string object, like adding or modifying an existing value, it will simply discard the old instance in memory and create a new instance to hold the new value.

 

For example, when we create a new string variablemsg” with the text “welcome”, a new instance will create a heap memory to hold this value. Now, if we make any changes to the msg variable, like changing the text from “welcome” to “welcome to tutlane”, then the old instance on heap memory will be discarded, and another instance will create on heap memory to hold the variable value instead of modifying the old instance in the memory.

 

Following is the pictorial representation of memory allocation for the string in the c# programming language.

 

C# String Memory Representation Diagram

 

In c#, if we perform modifications like inserting, concatenating, removing, or replacing a value of the existing string multiple times, every time the new instance will create on heap memory to hold the new value, so automatically the performance of the application will be affected.

C# String Literals (Regular, Verbatim)

In c#, the string literal is a sequence of characters enclosed in double quotation marks (" "). We have two kinds of string literals available in c#; those are regular and verbatim. The regular literals are useful when we want to embed escape characters like \n, \t, \', \", etc. in c#.

 

Following is the example of using regular string literals to embed escape characters in the c# programming language.

 

string names = "Suresh\nRohini\nTrishika";
Console.WriteLine(names);
/*
Output:
Suresh
Rohini
Trishika
*/
string msg = "Welcome to \"tutlane\" world";
Console.WriteLine(msg);
// Output: Welcome to "tutlane" world

In c#, the special character @ will serve as verbatim literal, and it is useful to represent a multiline string or a string with backslash characters, for example, to represent file paths.

 

Following is an example of using verbatim literal @ in c# programming language to represent a multiline string and a file path.

 

string path = @"C:\Users\Tutlane\Documents\";
Console.WriteLine(path);
//Output: C:\Users\Tutlane\Documents\

string msg = @"Hi Guest,
Welcome to Tutlane World
Learning Made Easy";
Console.WriteLine(msg);
/* Output:
Hi Guest,
Welcome to Tutlane World
Learning Made Easy
*/

string msg1 = @"My daughter name was ""Trishika.""";
Console.WriteLine(msg1);
//Output: My daughter name was "Trishika."

If you observe the above examples, we used a verbatim character @ to represent multiline strings or backslash character strings, etc., based on our requirements.

C# Format Strings

In c#, the format string is a string whose contents can be determined dynamically at runtime. We can create a format string using the Format method and embedding placeholders in braces that will be replaced by other values at runtime.

 

Following is the example of using a format string to determine the string content dynamically at runtime in the c# programming language.

 

string name = "Suresh Dasari";
string location = "Hyderabad";
string user = string.Format("Name: {0}, Location: {1}", name, location);
Console.WriteLine(user);
// Output: Name: Suresh Dasari, Location: Hyderabad

If you observe the above code, we are formatting a string using the Format method and replacing the placeholders in braces with required values.

C# Access Individual Characters from Strings

In c#, we can access individual characters from string by using array notation with index values.

 

Following is the example of accessing individual characters from the string by specifying the index position.

 

string name = "Suresh Dasari";
for (int i = 0; i < name.Length; i++)
{
Console.Write(name[i]);
}
// Output: Suresh Dasari

If you observe the above example, we are looping through characters in a string using for loop and displaying each character of the string based on the index position.

C# String Example

Following is the example of declaring and initializing strings, formatting string value, and using string literals to represent data in the c# programming language.

 

using System;

namespace Tutlane
{
     class Program
     {
        static void Main(string[] args)
        {
            string firstname = "Suresh";
            string lastname = "Dasari";
            string location = "Hyderabad";
            string name = firstname + " " + lastname;
            Console.WriteLine(name);
            string userInfo = string.Format("Name: {0}, Location: {1}", name, location);
            Console.WriteLine(userInfo);
            string names = "Suresh\nRohini\nTrishika";
            Console.WriteLine(names);
            string path = @"C:\Users\Tutlane\Documents\";           
            Console.WriteLine(path);
            string msg = @"Hi Guest,
            Welcome to Tutlane World
            Learning Made Easy";
            Console.WriteLine(msg);
            string msg1 = @"Her name was ""Trishika.""";
            Console.WriteLine(msg1);
            Console.WriteLine("\nPress Enter Key to Exit..");
            Console.ReadLine();
        }
     }
}

If you observe the above code, we declared and initialized string variables, formatted string using the Format method, and used string literals to embed escape characters, etc., based on our requirements.

 

When you execute the above c# program, you will get the result below.

 

C# Strings Example Result

 

This is how we can use strings in the c# programming language to represent a sequential collection of characters based on our requirements.

C# String Properties

The following table lists the available string properties in the c# programming language.

 

PropertyDescription
Chars It helps us to get the characters from the current string object based on the specified position.
Length It returns the number of characters in the current String object.

C# String Methods

In c#, the string class contains various methods to manipulate string objects based on our requirements.

 

The following table lists important string methods available in the c# programming language.

 

MethodDescription
Clone() It returns a reference to this instance of String.
Compare(String, String) It compares two specified String objects and returns an integer that indicates their relative position in the sort order.
Concat(String, String) It concatenates two specified instances of String.
Contains(String) It returns a value indicating whether a specified substring occurs within this string.
Copy(String) It creates a new instance of a String with the same value as a specified String.
Format(String, Object) It replaces one or more format items in a specified string with the string representation of a specified object.
Trim() It removes all leading and trailing white-space characters from the current String object.
ToLower() It converts a given string to a lowercase.
ToUpper() It converts a given string to uppercase.
Split(Char[]) It splits a string into substrings that are based on the characters in an array.
Substring(Int32) It retrieves a substring from this instance. The substring starts at a specified character position and continues to the end of the string.

This is how we can use strings in our applications to hold the required text in the c# programming language.