Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Strings
2.1.
Creation
2.2.
Immutable and mutable strings
3.
Escape sequences
4.
Interpolation
5.
Methods
5.1.
Example
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Strings in C#

Author Yashesvinee V
0 upvote
Leveraging ChatGPT - GenAI as a Microsoft Data Expert
Speaker
Prerita Agarwal
Data Specialist @
23 Jul, 2024 @ 01:30 PM

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
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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

FAQs

  1. 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.
     
  2. 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.

Key Takeaways

This article extensively discusses Strings in C#. We hope that this blog has helped you enhance your knowledge about the implementation of Strings in C#. 

Check out this problem - Multiply Strings

Related Links:


If you would like to learn more, check out our articles on the Coding Ninjas Library. Do upvote our blog to help other ninjas grow. Happy Coding!

Live masterclass