C# String with Examples

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

 

In c#, we use string keyword to create a 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 Length property we can know that, the number of characters the string variable is holding based on our requirements.

C# String Declaration and Initialization

Following are the different ways of declaring and initializing a string variables using string keyword in 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 above code snippet, we created a string variables using string and String keywords with or without initializing a values based on our requirements.

C# string vs String

If you observe above declarations, we used a two keywords called string and String to declare a 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 the naming convention you prefer to define a string variables.

C# String Immutability

In c#, string is immutable, it means the string object cannot be modified once it created. If any changes made to the string object like add or modify an existing value, then 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 text “welcome”, then a new instance will create on heap memory to hold this value. Now, if we make any changes to msg variable like changing the text from “welcome” to “welcome to tutlane”, then the old instance on heap memory will be simply 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 string in c# programming language.

 

C# String Memory Representation Diagram

 

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

C# String Literals (Regular, Verbatim)

In c#, string literal is a sequence of characters which are enclosed in double quotation marks (" "). We have a two kind 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 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 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 above examples, we used a verbatim character @ to represent a multiline strings or backslash character strings, etc. based on our requirements.

C# Format Strings

In c#, format string is a string whose contents can be determined dynamically at runtime. We can create a format string by using Format method and embedding a 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 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 above code, we are formatting a string using 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 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 above example, we are looping through a characters in string using for loop and displaying each character of string based on the index position.

C# String Example

Following is the example declaring and initializing a strings, formatting string value and use string literals to represent data in 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 above code, we declared and initialized a string variables, formatted string using Format method and used a string literals to embed escape characters, etc. based on our requirements.

 

When we execute above c# program, we will get the result like as shown below.

 

C# Strings Example Result

 

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

C# String Properties

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

 

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

C# String Methods

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

 

Following table lists an important string methods available in c# programming language.

 

MethodDescription
Clone() It returns a reference to this instance of String.
Compare(String, String) It compares a 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 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 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 c# programming language.