简体   繁体   中英

C# replace item in list<string> “/”

I want\\need to change specific char with another char inside a list

I want to change "A" with "\\P\\;"

this is what I have done

for (int i = 0; i < msg.Count; i++)
{
    msg[i] = msg[i].Replace("A", "\P\;");
}

but I get this error: "Unrecognized escape sequence"


The problem is that it doesn't change it to HEX after it.

so this is what I have thought to do :

List<string> changeOne = new List<string>
for (int i=0;i<msg.Count();i++)
{
if msg[i] == "A" 
{
changeOne[i] = "\";
change[One[i+1] = "p";
}
i++;
}

can I do something like this? how do make it to work? because i think I will have problems

let say the msg list is this :

0-D
1-A
2-S
3-1

I want the changeOne list to be like this

0-D
1-\
2-p
3-\
4-;
5-S
6-1

Thanks ,

Try using verbatim string literal - anything in the string that would normally be interpreted as an escape sequence is ignored.

ex : C:\\\\Users\\\\Rich is the same as @"C:\\Users\\Rich"

Exemple

In your case:

msg[i] = msg[i].Replace("A", @"\P\;");

When you don't want a literal value escaped in C# you can use the Verbatim String marker.

In this case, replace "\\P\\;" with @"\\P\\;" this is much easier to understand then having multiple escapes in a string.

The main problem is that your question is not too clear. You want to replace one string with 4 strings.

1-A

becomes

1-\
2-p
3-\
4-;

in your example.

List<string> changeOne = new List<string>
for (int i=0;i<msg.Count();i++)
{
   if (msg[i] == "A")
   {
     changeOne.AddRange( new [] {"\\","p","\\",";" });
   }
   else
   {
          changeOne.Add(msg[i]);
   }
}

The backslash ("\\") character is a special escape character you need to use two backslashes or use the @ verbatim string.

for (int i = 0; i < msg.Count; i++)
        {
            msg[i] = msg[i].Replace("A", "\\P\\;");
            //or
            msg[i] = msg[i].Replace("A", @"\P\;");
        }

You can refer to this link : Escape Sequences

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM