Course C# Programming Basics for Beginners
.Net C# CSharp

String manipulations

( 0 users )

Strings

In C#, a string is reference type data type that is used to represent a sequence of characters. It is declared with "string" keyword which is a wrapper around System.String class. We can also say that string is an array of characters represented in a concise way. String manipulation is a very important feature in any programming language because it is used to operate on textual data. In general, we can declare a string as follows.


string name;
		

Here name is a variable of string data type. To initialize a string, we simply assign a string literal to it.


string name = "Alice";
		

We can simply use it just like any other variable. The following line will print "Alice".


Console.WriteLine(name);
		

We can also create string type variable from character array. The string constructor can take a character array type of argument to initialize a string.


char[] nameArray = {'A', 'l', 'i', 'c', 'e'};
string name = new string(nameArray);
		

String Concatenation

To concatenate two strings we use "+" operator. We did use "+" operator in the example in previous chapters. The below example will print "Hello World" to the console.


	var message = "Hello " + "World";
	Console.WriteLine(message);
			

Strings are immutable

Consider the below example.


	string name = "Alice";
	name = "Bob";
			

In the above example, the first statement will assign value "Alice" to variable "name". This value will be stored in the heap in memory. When the next statement gets executed, a new memory location will be allocated in the heap. The previous value in the heap will remain as it is unless the garbage collector cleans it up.

This is important to know because generally in programming we do a lot of string manipulation specially concatenation. So we must avoid such kind of extensive string manipulations because it will unintentionally consume memory.

Escape Characters

In C#, string literals allows us to provide certain escape characters which have some special meaning and provides certain behaviour. Some of those frequently used escape characters are "\n", "\t", "\"", "\\" etc. Let's see the below examples.


// 1. This will print "World" in the next line.
Console.WriteLine("Hello\nWorld");

// Output
/*
Hello
World
*/

// 2. This will create a tab space.
Console.WriteLine("Hello\tWorld");

// Output -
// Hello 	World

// 3. This will allow to use double quotes (") in a string literal (Normally we can't use this character because it indicates the start or end of string literal).
Console.WriteLine("\"Hello World\"");

// Output - 
// "Hello Word"

// 4. This will allow us to use backward slash (\) in a string literal (Normally we can't use this character because it indicates the start of an escape character in a string literal)

Console.WriteLine("D:\\Projects\\csharp\\Program.cs");

// Output - D:\Projects\csharp\Program.cs
			

Note : There is an additional character "@" called "verbatim" which is used to write a string literal with backslash and newline without using the corresponding escape characters. Let's see an example.


var message = @"Hello Alice,
	
Good morning!

Your files have been saved to this location.
\shared\alice

Thanks.";

Console.WriteLine(message);

/* This will print the following output

Hello Alice,

Good Morning!

Your files have been saved to this location.
\shared\alice

Thanks.

*/
			

String Interpolation

There are couple of ways in which we can manipulate string. Let's see those.

String.Format()

The "String.Format()" method takes a string literal as its first argument. In the rest of the arguments, we can pass values and variables which replace specific positions in the string defined by a place-holder - { }. Let see the below example.


var name = "Alice";

var greeting = String.Format("Hello {0}, {1}!", name, "good morning");

Console.WriteLine(greeting);
			

In the above example, {0} will be replaced by values of "name" and {1} will be replaced by the string literal "good morning". The output would be "Hello Alice, good morning!"

The "$" prefix

This is very powerful and clean way of doing string interpolation which was introduced in C# 6.0. We can write any valid C# expression inside a string itself. In this, we prefix the string with "$" symbol. Let's see with an example.


var name = "Alice";
var greet = "good morning";

var greeting = $"Hello {name}, {greet}!";

Console.WriteLine(greeting);
			

In the above example, the variables name and greet replace the placeholders - {name} and {greet}. This will output the same string as in previous example - "Hello Alice, good morning!". Let's see another example.


var num = 12;
Console.WriteLine($"Square of { num } = { num * num }");
			

Since the placeholders can take any valid C# expression, the above statement will output - "Square of 12 = 144" to the console. You can try with different valid C# expressions inside the placeholder.

Other string methods

Here are some of the commonly used string methods in C#.

  • Substring : It is used to get sub-string from a given string.

    
    var text = "Hello World";
    
    var sub_text = text.Substring(6, 5);
    
    Console.WriteLine(sub_text);
    
    // Output : World
    				
  • ToUpper : It is used to convert the string into upper case letters.

    
    var text = "Hello World";
    Console.WriteLine(text.ToUpper());
    
    // Output : HELLO WORLD
    				
  • ToLower : It is used to convert the string into lower case letters.

    
    var text = "Hello World";
    Console.WriteLine(text.ToLower());
    
    // Output : hello world
    				
  • Trim : It is used to remove the spaces before first character and after last character of a string.

    
    var text = "    Hello World         ";
    Console.WriteLine(text.Trim());
    
    // Output : Hello World
    				
  • Split : It is used to split a string into a string array based on a specific delimiter present in the string. The Split method takes a parameter called delimiter which is used to specify the splitting point within the string.

    
    var csv = "Alice,Bob,Chris,Dave,Eric,Fred";
    
    var names = csv.Split(','); 
    
    for( var i = 0; i < names.Length; i++)
    {
    	Console.WriteLine(names);
    }
    
    /* Output
    
    Alice
    Bob
    Chris
    Dave
    Eric
    Fred
    
    */
    				
  • Contains : It is used to check whether a string contains a given substring or not.

    
    var greet = "Hello World";
    
    if(greet.Contains("World"))
    {
    	Console.WriteLine("World is a substring of {0}", greet);
    }
    				
  • Replace : It is used to replace a part of string with another string.

    
    var greet = "Hello World";
    
    var newGreet = greet.Replace("World", "Team");
    
    Console.WriteLine(newGreet);
    
    // Output : Hello Team
    				
  • IndexOf : It returns the index of the first occurrence of a specified character or string.

    
    var greet = "Hello Alice. Welcome";
    
    var index = greet.IndexOf("el");
    
    Console.WriteLine(index);
    
    // Output
    
    1
    				
  • LastIndexOf : It returns the index of the last occurrence of a specified character or string.

    
    var greet = "Hello Alice. Welcome";
    
    var index = greet.LastIndexOf("el");
    
    Console.WriteLine(index);
    
    // Output
    
    14
    				

Here is the complete code below showing all different methods of string manipulations as described above.

Run this code


using System;

class Program
{
	static void Main(string[] args)
	{
		Console.WriteLine("-- Strings --");
		Console.WriteLine("");
		
		Console.WriteLine("-- Simple String --");
		Console.WriteLine("");
		
		string name = "Alice";
		Console.WriteLine(name);
		
		Console.WriteLine("");
		Console.WriteLine("-- String from char array --");
		Console.WriteLine("");
		
		char[] nameArray = {'A', 'l', 'i', 'c', 'e'};
		name = new string(nameArray);
		Console.WriteLine(name);
		
		Console.WriteLine("");
		Console.WriteLine("-- String Concatenation --");
		Console.WriteLine("");
		
		var message = "Hello " + "World";
		Console.WriteLine(message);
		
		Console.WriteLine("");
		Console.WriteLine("-- Escape characters --");
		Console.WriteLine("");
		
		Console.WriteLine("Hello\nWorld");
		Console.WriteLine("Hello\tWorld");
		Console.WriteLine("\"Hello World\"");
		Console.WriteLine("D:\\Projects\\csharp\\Program.cs");
		
		Console.WriteLine("");
		Console.WriteLine("-- Verbatim --");
		Console.WriteLine("");
		
		message = @"Hello Alice,
	
Good morning!

Your files have been saved to this location.
\shared\alice

Thanks.";

		Console.WriteLine(message);
		
		Console.WriteLine("");
		Console.WriteLine("-- String Interpolations --");
		Console.WriteLine("");
		
		name = "Alice";
		var greeting = String.Format("Hello {0}, {1}!", name, "good morning");
		Console.WriteLine(greeting);
		
		name = "Alice";
		var greet = "good morning";
		greeting = $"Hello {name}, {greet}!";
		Console.WriteLine(greeting);
		
		var num = 12;
		Console.WriteLine($"Square of { num } = { num * num }");
		
		Console.WriteLine("");
		Console.WriteLine("-- Other string methods --");
		Console.WriteLine("");
		
		var text = "Hello World";
		Console.WriteLine($"text = {text}");
		Console.WriteLine($"text.Substring(6, 5) : {text.Substring(6, 5)}");
		Console.WriteLine($"text.ToUpper() : {text.ToUpper()}");
		Console.WriteLine($"text.ToLower() : {text.ToLower()}");
		
		Console.WriteLine("");
		text = "    Hello World         ";
		Console.WriteLine($"text = {text}");
		Console.WriteLine($"text.Trim() : {text.Trim()}");
		
		var csv = "Alice,Bob,Chris,Dave,Eric,Fred";
		Console.WriteLine($"csv = {csv}");
		var names = csv.Split(','); 
		Console.WriteLine("csv.Split(\",\")");
		for( var i = 0; i < names.Length; i++)
		{
			Console.WriteLine(names[i]);
		}
		
		Console.WriteLine("");
		text = "Hello World";
		Console.WriteLine($"text = {text}");
		Console.WriteLine($"text.Contains(\"World\") : {text.Contains("World")}");
		
		Console.WriteLine($"text.Replace(\"World\", \"Team\") : {text.Replace("World", "Team")}");
		
		Console.WriteLine("");
		greet = "Hello Alice. Welcome!";
		Console.WriteLine($"greet = {greet}");
		Console.WriteLine($"greet.IndexOf(\"el\") : {greet.IndexOf("el")}");
		Console.WriteLine($"greet.LastIndexOf(\"el\") : {greet.LastIndexOf("el")}");
		
		Console.Write("Press any key to continue...");
		Console.ReadKey(true);
	}
}
		

To Do

* Note : These actions will be locked once done and hence can not be reverted.

1. Track your progress [Earn 200 points]

2. Provide your ratings to this chapter [Earn 100 points]

0