Reader Level:
Articles

Add, Remove, Replace Strings in C#

By Mahesh Chand on August 21, 2010
This code snippet shows how to add, remove and replace strings in C#.
  • 0
  • 0
  • 32824


Adding, Removing and Replacing Strings

TheInsert method inserts a specified string at a specified index position in an instance. For example, the following source code inserts "bbb" after second character in str1 and the result string is "pbbbpp".

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

TheRemove method deletes a specified number of characters from a specifiedposition in a string. This method returns result as a string. For example, the following code removes three characters from index 3.

string s = "123abc000";
Console.WriteLine(s.Remove(3, 3));

TheReplace method replaces all occurrences of a specified character in a string. For example, the following source code replaces all p character instances of str1 with character l and returns string "lll".

string str1 = "ppp";
string repStr = str1.Replace('p', 'l');
Console.WriteLine("Replaced string:"+ repStr.ToString() );

TheSplit 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() );
}



Read C# Strings  to learn more about strings in C#.

Mahesh Chand

Mahesh Chand is founder of C# Corner. C# Corner founded in 1999 is a FREE member contributions based open platform for developers to solve problems, learn new technology and hang out.  Mahesh has been awar... Read more

COMMENT USING

Trending up