C# tutorials
15. Replace with array and string

Note: While reading this page, bear in mind that I'm no computer expert and that the text below may be partly inaccurate. If you find errors or have proposals for improvements, please send me a message and help make this a better page for the benefit of future visitors. To the left, there are links to more C# tutorials.


To complete this tutorial, follow these instructions:

1. Open Visual C# 2010 Express.

2. Click on New Project in the File menu.

3. Choose Windows Forms Application if that option isn't already chosen, change the name if you like and click on OK.

4. Point at Toolbox in the left margin and click on the Auto Hide icon at the top of the window (to keep the window to stay open and easier to work with).

5. Drag a Button to Form 1.

6. Drag a Rich Textbox to Form 1. Resize the textbox if you like.

7. Double-click on the button. The file Form1.cs will open with the caret ready to write code that will run when button 1 is clicked.

8. Write or paste this code where the caret is:

try
{
  string[] Old = { "soup", "milk", "candy" };
  string New = "beer";
  richTextBox1.Text = mkReplace(richTextBox1.Text, Old, New);
}
catch (Exception excMsg)
{
  MessageBox.Show(excMsg.Message.ToString(), "Error");
}

9. Write or paste this code right above the line private void button1_Click(object sender, EventArgs e):

public string mkReplace(string str, string[] Old, string New)
{
  for (int i = 0; i < Old.Length; i++)
  {
    str = str.Replace(Old[i], New);
  }
  return str;
}

10. Press F5 to start debugging the program.

11. Write or paste this text to the textbox: I like soup, milk and candy.

12. Click on the button. The text should change to: I like beer, beer and beer.

Comment on the first code snippet

Line 3-5: Replace soup, milk and candy with beer.

Comment on the second code snippet

Line 3-6: Replace each value in the array Old with the string New.

More

I think this method is especially useful if you want to remove several strings. To remove each value in the array Old, change line 4 in the first code snippet to:

string New = "";

"" is an empty string.

See also comments on C# tutorials: 14. Replace with two arrays.


Would you like to comment on this page or some other page? Use the contact form. Write the title of the page you want to comment on and your comment in the field Message.