C# - Replace a character with nothing
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
strin开发者_运维技巧g[] 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 "."?
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(".",""));
string item2 = item.Replace(".", "");
You need to use the result of Replace
, it doesn't operate on the string itself.
Instead of the "" use String.Empty. In this way there is no new object created.
Instead of:
item.Replace(".", "");
Try this:
item = item.Replace(".", ""); (edit: this was my original idea, but it's wrong)
placementOneListBox.Items.Add(item.Replace(".", ""));
Strings are immutable, so
item.Replace(".","")
does not modify item, but returns a new string.
You need to use:
placementOneListBox.Items.Add(item.Replace(".",""));
Edit: and as you can see from the flurry of simultaneous responses, many of our peers agree! ;-)
Replace your replace:
item.Replace(".","");
with this:
item = item.Replace(".","");
How about
// Splits the lines in the rich text boxes string[] listOneLines = oneRichTextBox.Text.Replace(".","").Split('\n');
精彩评论