Add, Remove, Replace String In C#

Add or Concatenate Strings In C#

Adding strings is also known as concatenating strings. We can add two strings in C# by simply using the + operator. Here is a detailed article on this, 6 Effective Ways To Concatenate Strings In C#

We can also insert a string at a specified position in another string. String.Insert method inserts a specified string at a specified index position in an instance. For example, the following code inserts "bbb" after the second character in str1, and the result string is "pbbbpp".

string str1 = "ppp";  
string strRes = str1.Insert(2, "bbb");  
Console.WriteLine(strRes.ToString());  

String Interpolation is the most effective way to add strings. Learn more here, Understanding String Interpolation in C#.

Remove String In C#

String.Remove() method removes a given number of characters from a string at a specified position. The position is a 0-index position. That means the 0th position is the first character in the string.

In C#, Strings are immutable. That means the method does not remove characters from a string. The method creates and returns a new string without those characters.

String.Remove() method has two overloaded forms.

Method Description
Remove(Int32) Returns a new string in which all the characters in the current instance, beginning at a specified position and continuing through the last position, have been deleted.
Remove(Int32, Int32) Returns a new string in which a specified number of characters in the current instance beginning at a specified position has been deleted.

Example 1

The following example removes all characters from a string that are after the 25th position in the string.

string founder = "Mahesh Chand is a founder of C# Corner";  
// Remove all characters after first 25 chars  
string first25 = founder.Remove(25);  
Console.WriteLine(first25);  

The following example removes 12 characters from the 10th position in the string.

// Remove characters start at the 10th position, next 12 characters  
String newStr = founder.Remove(10, 12);  
Console.WriteLine(newStr);  

Example 2

Now, let’s say you want to delete everything after or before a substring in a string. We can use String.IndexOf() to find the position of the substring and can use the starting index and number of characters to remove.

The following example removes everything before and after substring ‘founder’ in a string.

// Remove everything after founder  
int pos = founder.IndexOf("founder");  
if (pos >= 0) {  
    // String after founder  
    string afterFounder = founder.Remove(pos);  
    Console.WriteLine(afterFounder);  
    // Remove everything before founder but include founder  
    string beforeFounder = founder.Remove(0, pos);  
    Console.Write(beforeFounder);  
}  

The complete program is listed in Listing 1.

using System;  
namespace RemoveStringSample {  
    class Program {  
        static void Main(string[] args) {  
            /** Remove sample **/  
            string founder = "Mahesh Chand is a founder of C# Corner";  
            // Remove all characters after first 25 chars  
            string first25 = founder.Remove(25);  
            Console.WriteLine(first25);  
            // Remove characters start at 10th position, next 12 characters  
            String newStr = founder.Remove(10, 12);  
            Console.WriteLine(newStr);  
            int pos = founder.IndexOf("founder");  
            if (pos >= 0) {  
                // String after founder  
                string afterFounder = founder.Remove(pos);  
                Console.WriteLine(afterFounder);  
                // Remove everything before founder but include founder  
                string beforeFounder = founder.Remove(0, pos);  
                Console.Write(beforeFounder);  
            }  
            Console.ReadKey();  
        }  
    }  
}  

Listing 1.

Replace Strings In C# 

String.Replace() method replaces a character or a string with another character or string in a string. 

In C#, Strings are immutable. That means the method does not replace the characters or strings from a string. The method creates and returns a new string with new characters or strings.

String.Replace() method has two overloaded forms.

Method Description
Replace(Char, Char) Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced with another specified Unicode character.
Replace(String, String) Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Example 1

The following example replaces all commas with a colon in a string.

// Replace a char  
string odd = "1, 3, 5, 7, 9, 11, 13, 15, 17, 19";  
Console.WriteLine($ "Original odd: {odd}");  
string newOdd = odd.Replace(',', ':');  
Console.WriteLine($ "New Odd: {newOdd}");  

The following example replaces all “Beniwal” with an empty string so only first names are copied to the new string.

string authors = "Mahesh Beniwal, Neel Beniwal, Raj Beniwal, Dinesh Beniwal";  
Console.WriteLine($ "Authors with last names: {authors}");  
// Remove all Beniwal with space and remove space with empty string  
string firstNames = authors.Replace(" Beniwal", "");  
Console.WriteLine($ "Authors without last names: {firstNames}");  

The complete program is listed in Listing 1.

using System;  
namespace ReplaceStringSample {  
    class Program {  
        static void Main(string[] args) {  
            /** Replace sample **/  
            // Replace a char  
            string odd = "1, 3, 5, 7, 9, 11, 13, 15, 17, 19";  
            Console.WriteLine($ "Original odd: {odd}");  
            string newOdd = odd.Replace(',', ':');  
            Console.WriteLine($ "New Odd: {newOdd}");  
            string authors = "Mahesh Beniwal, Neel Beniwal, Raj Beniwal, Dinesh Beniwal";  
            Console.WriteLine($ "Authors with last names: {authors}");  
            // Remove all Beniwal with space and remove space with empty string  
            string firstNames = authors.Replace(" Beniwal", "");  
            Console.WriteLine($ "Authors without last names: {firstNames}");  
            Console.ReadKey();  
        }  
    }  
}  

Listing 1.

The output of Listing 1 looks like Figure 1.

C# String Replace

Figure 1.

The Split method separates strings by a specified set of characters and places these strings into an array of strings. For example, the following source code splits strArray based on ',' and stores all separated strings in an array.

string str1 = "ppp";  
string str2 = "ccc";  
string str3 = "kkk";  
string strAll3 = str1 + ", " +str2+", "+str3 ;  
string[] strArray = strAll3.Split(',');  
foreach (string itm in strArray)  
{  
   Console.WriteLine(itm.ToString() );  
}  

The output from the above code is shown below.

c# string 

Conclusion

To learn more about C# strings, check out the String In C# tutorial to learn more about strings and how to work with strings in C#.


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.