C # string.Replace not working

Basically our problem: We cannot replace the string as follows: 10003 * But we can replace the string as follows: 10003

we want to replace the part of the line that looks like this: 10003 * This is our code:

string text = sr2.ReadToEnd(); sr2.Close(); while (loop != lstTxt.Items.Count) { string SelectedItem = lstTxt.SelectedItem.ToString() + "*"; text = text.Replace(SelectedItem, "tietze111"); if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1) lstTxt.SelectedIndex++; loop++; } sw2.Write(text); 

But that will not work. When we leave * in the replacement part, it works. But we must also replace *. Do you know what we need to change?

It works when we use this:

 string text = sr2.ReadToEnd(); sr2.Close(); while (loop != lstTxt.Items.Count) { string SelectedItem = lstTxt.SelectedItem.ToString(); // changed text = text.Replace(SelectedItem, "tietze111"); if (lstTxt.SelectedIndex < lstTxt.Items.Count - 1) lstTxt.SelectedIndex++; loop++; } sw2.Write(text); 

- using (var sr2 = new StreamReader (Application.StartupPath + @ "\ website \ Dehler 22 ET.htm", Encoding.Default)) {

  using (var sw2 = new StreamWriter(tempFile, true, Encoding.Default)) 

We use this because the file is still in ASCII. Perhaps this is the problem. How do we solve this?

0
source share
4 answers

Correct the following line,

 string SelectedItem = lstTxt.SelectedItem.Value; 

You take an element, not a value.

0
source

You tried?

 "[\*]" 

or

 @"[*]" 
0
source

The String.Replace(String,String) method does nothing special with any characters. Your identifier that you are trying to replace has a character that does not match the one you are trying to execute. I would try copying astrisk from the data source to your code and see if there is a problem.

0
source

Your problem * is encoded by some other type. Unicode value for asterisk U + 002A

You can try this. Note Char.MinValue is technically a null value since you cannot have an empty Char.

In your case: lstTxt.SelectedItem.ToString() + '\u002A'.ToString();

If this does not work, try deleting (using different encoded values ​​for *) to make sure you can really find it in the string.

 SomeString.Replace('\u002A', Char.MinValue); 

OR

 SomeString.Replace('\u002A'.ToString(), String.Empty); 

I ran into problems like before, and it ends up being a trial version and an error until you fix it. I had a similar problem last summer C # String.Replace not find / replace Symbol (™, ®)

0
source

Source: https://habr.com/ru/post/1478848/


All Articles