C# - Replace a character with nothing

theNoobGuy picture theNoobGuy · Jul 26, 2011 · Viewed 40.7k times · Source

I have a RichTextBox that looks like this:

TEXT  NEXT_TEXT  10.505   -174.994 0
TEXT  NEXT_TEXT  100.005  174.994  90 
TEXT  NEXT_TEXT  -10.000  -5.555   180
TEXT  NEXT_TEXT  -500.987 5.123    270
TEXT  NEXT_TEXT  987.123  1.000    180
TEXT  NEXT_TEXT  234.567  200.999  90

and I want to replace the "." with nothing and place it into a ListBox...

So the new file would look like this:

TEXT  NEXT_TEXT  10505   -174994 0
TEXT  NEXT_TEXT  100005  174994  90 
TEXT  NEXT_TEXT  -10000  -5555   180
TEXT  NEXT_TEXT  -500987 5123    270
TEXT  NEXT_TEXT  987123  1000    180
TEXT  NEXT_TEXT  234567  200999  90

I thought about multiplying the values by 1000 but I do not know how to properly do match calculations on a string.

So the next thought was to do this (HOWEVER THIS DOES NOT WORK):

  // Splits the lines in the rich text boxes
  string[] listOneLines = oneRichTextBox.Text.Split('\n');

  // Set the selection mode to multiple and extended.
  placementOneListBox.SelectionMode = SelectionMode.MultiExtended;

  // Shutdown the painting of the ListBox as items are added.
  placementOneListBox.BeginUpdate();

  // Display the items in the listbox.
  foreach (var item in listOneLines)
  {
      item.Replace(".","");
      placementOneListBox.Items.Add(item);
  }

  // Allow the ListBox to repaint and display the new items.
  placementOneListBox.EndUpdate();

  • Can anyone help me figure out how to replace a "."?

Answer

David Heffernan picture David Heffernan · Jul 26, 2011

Strings are immutable so this line is wrong:

item.Replace(".","");

This returns the string after the replacement has been made, but item is unchanged. You need this:

foreach (var item in listOneLines)
    placementOneListBox.Items.Add(item.Replace(".",""));