C# String

Sytem.String or string, is one of most widely used data type in C#. String is defined as a sequence of characters. In C#, we store string inside double quotes ("somestring").

Syntax for Declaring and initiliazing string

// Declare without initializing.
string str;

// Initialize to null.
string str1= null;

//declare and initializing string with some value
string str2="Hello World";

We can manipulate strings in several ways, but here we will see examples of most common and widely used.

Let's create a simple program to print a normal string variable in C#

using System;
					
public class Program
{
	public static void Main()
	{
		 string tutorial = "C-Sharp"; 
		 Console.WriteLine(tutorial); 	

	}
}

Output:

C-Sharp

Using escape Characters in C# string

Suppose you want to use Escape characters inside string like "\" , we cannot do it like regular manner

string str = "C:\test"; //this will not work and give error, unrecognised escape sequence

so, we need to initialize and declare it like

string str ="C:\\test";   //now, this will work

Basically, in C#, we use "\" as escape characters like double quote ("), single quote ('), backslash (\).

But when we have a long string which contains multiple characters like double quote, single quote etc, we can append "@" at the beginning of the string and can use it like below

string str =@"C:\test\csharp\file.html";

So the second method is preferred one.

Format string in C#

A format string is a string whose contents are determined dynamically at runtime. The string.format method formats a string.

Format strings are created by embedding interpolated expressions or placeholders inside of braces within a string.

String interpolation

Available in C# 6.0 and later, Interpolated strings are identiified by $ special character, take a look at an example

var str = (firstName: "Vikas", lastName: "Lalwani", born: 1991);
Console.WriteLine($"{str.firstName} {str.lastName} is a developer born in {str.born}");

//output
// Vikas lalwani is a developer born in 1991.

String interpolation improves readability of code.

Composite Formatting

String.Format is used when we talk about composite formatting, it utilizes placeholders in braces to create a formatted string. Take a look at the below example, in which we will format currency

		double currency = 10.5;
		string strFormat; 
		strFormat = string.Format("Your balance is {0:C}", currency);
		
		Console.WriteLine(strFormat);

Output

Your balance is $10.50

We can also append format usual string like this

string str = "Name:{0} {1}, Location:{2}, Age:{3}";

string msg = string.Format(str, "Jaya", "Dasari", "Delhi", 32);
Console.WriteLine("Format Result: {0}", msg);

Output:

Format Result: Name:Jaya Dasari, Location:Delhi, Age:32

Here is the Complete example

using System;
					
public class StringProgram
{
	public static void Main()
	{
		double currency = 10.5;
		string strFormat; 
		strFormat = string.Format("Your balance is {0:C}", currency);
		
		Console.WriteLine(strFormat);


		string str = "Name:{0} {1}, Location:{2}, Age:{3}";

        string msg = string.Format(str, "Jaya", "Dasari", "Delhi", 32);
        Console.WriteLine("Format Result: {0}", msg);
	}
}

Output:

Your balance is $10.50
Format Result: Name:Jaya Dasari, Location:Delhi, Age:32

String Concatenation in C#

Concatenation is joining two (or more) things together (in this case strings). Strings in C# can be added using the + operator or the Concat() method. They will form a new string which is a chain of all concatenated strings. 

Here is the simple example of of string concatenation in C#

string name="John Wick";
Console.WriteLine(name + " lives in New York");

Output:

John Wick lives in New York

Manipulating Strings in C#

We have multiple built-in methods in C# to manipulate strings. Let's take a look on widely used methods one by one:

Substring

A substring is any sequence of characters that is contained in a string. Use the Substring method to create a new string from a part of the original string.

Example:

        string s3 = "Hello World";
        Console.WriteLine(s3.Substring(7, 2));
        //output : or

In the above example, the substring starts at a specified character position and has a specified length.

Another overloaded method of .Substring(int) takes one argument, and substring starts at a specified character position and continues to the end of the string.

IndexOf

It reports the zero-based index of the first occurrence of a specified Unicode character or string within this instance, for example

               int index = s3.IndexOf("W");
		Console.WriteLine(index);      

In the above example, consdering s3="Hello World", output = 6, as "W" is first placed at 6th position of string s3.

Replace

The replace method replaces a string. It takes two parameters, the old string and new string. It can also take chars, example:

s3=s3.Replace("Hello", "Bye");
Console.WriteLine(s3);
//output: bye world

Complete Example

using System;
					
public class Program
{
	public static void Main()
	{
		string s3 = "Hello World";
        Console.WriteLine(s3.Substring(7, 2));
		
		int index = s3.IndexOf("W");
		Console.WriteLine(index);
        
		s3=s3.Replace("Hello", "Bye");
		Console.WriteLine(s3);
			
	}
}

Output:

or
6
Bye World

Contains

Contains methods check if a substring is present in the main string, if yes returns true, otherwise false

ToUpper()

ToUpper method converts all characters of string into Uppercase.

ToLower()

ToLower method converts all characters of string into Lowercase.

Length

Length methods counts the number of characters in a string

Example:

           string word = "Determination";

            Console.WriteLine(word.Contains("e"));           
            Console.WriteLine(word.ToUpper());
            Console.WriteLine(word.ToLower());
            Console.WriteLine(word.Length);

Output:

True
DETERMINATION
determination
13

Share Tweet