Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Strings are a sequence of characters enclosed within double-quotes. It represents an array of characters under a single variable. The difference between a character array and a string is that in a character array, the size has to be allotted at the time of declaration and cannot be altered at run time. However, in strings, there is no need to specify the size to allocate fixed memory at the time of declaration.
Every program uses strings for various purposes. In C#, String is a part of the System.String class. It provides different methods to manipulate strings according to the programmer’s choice.
Strings
Creation
We use the string keyword to declare a string variable and initialise the value within double-quotes.
using System;
namespace CsString {
class NewString {
public static void Main(string [] args) {
// create string
string str = "Hello World";
// print string
Console.WriteLine("Programming with C#");
Console.WriteLine(str1);
Console.ReadLine();
}
}
}
Output:
Programming with C#
Hello World
Immutable and mutable strings
Strings are immutable, i.e. they cannot be changed once created. This means that every time we try to modify the string, a new string object is created in place of the original. The initial string str is concatenated with another string to create a new string object.
using System;
namespace CsString {
class CString {
public static void Main(string [] args) {
string str = "Hello";
Console.WriteLine(str);
str = string.concat(str, " WORLD");
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output:
Hello
Hello World
Mutable strings can be modified dynamically without creating a new string object. These strings are created using the StringBuilder class. The Append method combines two strings.
using System;
using System.Text;
namespace CsString {
class NewString {
public static void Main(string [] args) {
StringBuilder str = new StringBuilder("Hello");
str.Append(" World");
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output:
Hello World
Escape sequences
Escape sequences hold a special meaning when used inside a string. They are escaped using the backslash character. Given below are the escape sequences used in C#.
using System;
namespace CsString {
class NewString {
public static void Main(string [] args) {
string str = "\”Hello World\” is a string";
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output:
"Hello World" is a string
Interpolation
We can print the values of variables as a part of the string. This is called string interpolation. In order to implement string interpolation, the string must start with a ‘$’ symbol. The variable to be printed is written within { } at the required position. Here is an example.
using System;
namespace CsString {
class CString {
public static void Main(string [] args) {
// create string
string name = "Coding Ninjas Studio";
// string interpolation
string message = $"Welcome to {name}";
Console.WriteLine(message);
Console.ReadLine();
}
}
}
Output:
Welcome to Coding Ninjas Studio
Methods
Method/Property
Description
Length
It returns the length of the string.
Format()
It returns a formatted string.
Concat()
It joins two given strings.
Split()
It splits a string into two or more parts.
Substring()
It returns a substring of a string.
Equals()
It returns true if two strings are equal.
Compare()
It compares two strings in terms of their ASCII value. It returns 0 if they are the same, -1 or +1 if one is greater than the other.
Replace()
It replaces a substring in a string with another string.
Contains()
It checks if the given substring exists in the string.
Join()
It joins two strings using the given separator.
Trim()
It removes any leading or trailing whitespaces in the string.
EndsWith()
It returns true if a string ends with the given character or string.
IndexOf()
It returns the index of a given character in a string.
Remove()
It deletes all occurrences of a character or substring in the string.
ToUpper()
It converts all lower case characters in the string to uppercase.
ToLower()
It converts all uppercase characters in the string to lower case.
PadLeft()
It returns a string padded with spaces or a character on the left.
PadRight()
It returns a string padded with spaces or a character on the right.
StartsWith()
It returns true if a string starts with the given character or string.
ToCharArray()
It converts the string into a character array.
LastIndexOf()
It returns the index of the last occurrence of a substring or character.
Example
using System;
namespace CsString {
class StringProgram {
public static void Main(string [] args) {
string str1 = "ABCDEF";
Console.WriteLine($"String 1: {str1} Length: {str1.Length}\n");
string str2 = "abcdef";
Console.WriteLine($"String 2: {str2} Length: {str2.Length}");
Console.WriteLine($"String 1 and String 2 are equal: {str1.Equals(str2)}");
str1 = str1.ToLower();
Console.WriteLine($"String 1 to lowercase: {str1}" );
Console.WriteLine($"String 1 and String 2 are equal: {str1.Equals(str2)}");
string str = string.Concat(str1, str2);
Console.WriteLine($"Concatenated string: {str}");
Console.WriteLine($"First Index of b: {str.IndexOf('b')}");
Console.WriteLine($"Last Index of d: {str.LastIndexOf('d')}");
Console.ReadLine();
}
}
}
Output:
String 1: ABCDEF Length: 6
String 2: abcdef Length: 6
String 1 and String 2 are equal: False
String 1 to lowercase: abcdef
String 1 and String 2 are equal: True
Concatenated string: abcdefabcdef
First Index of b: 1
Last Index of d: 9
Frequently Asked Questions
What is the difference between Concat and Join?
Concat is used to join two strings without a separator. Join is used to join a set of strings using a separator.
What happens when we try to access a character from a string outside the string size?
The index of the last character in the string is Length-1. Attempting to access a character of index beyond this value will result in IndexOutOfRangeException.
Are strings mutable in C#?
No, strings in C# are immutable, meaning their values cannot be changed after creation. Modifying a string creates a new string object.
Conclusion
In this article, we discussed strings in C#, covering their properties, methods, and how to manipulate them efficiently. We learned that strings in C# are immutable, meaning any operation on a string creates a new instance. Understanding the different ways to handle strings, such as using the String class methods and StringBuilder, can greatly improve performance and make string manipulation more efficient in C# applications.