c# - 替换在某些情况下不起作用

标签 c# string replace

我有以下字符串。

We all know you can never have too many yoga pants!! Today's giveaway is with my fav @aloyoga \ud83d\ude0d \ud83c\udf81\ud83d\udcaa\ud83c\udffcI am honestly so proud of everyone who has been participating in the #JenSelterChallenge.. I have been overwhelmed by the level of commitment, progress, and positivity over the last couple of weeks. Seeing your photos and captions puts a huge smile on my face everyday. Thank you guys for making it such a success and for those who haven't joined yet, it's not too late! Congrats to the winners of WEEK 3\u2014 I will DM you all this weekend!! \ud83d\ude03 \n@Vicfitness_\n@Bodyroxxfit\n@Krvstah\n@Lvlelissa3\n@ThisIsNaila \n@X_i_a_r_a_\n@Btrevellini\n@Nicolesfitjourney_ \n#Seltering

我想用 Environment.NewLine 替换\n。所以,我尝试了以下方法:

caption = caption.Replace("\n", Environment.NewLine);

没用。什么都没有改变。我在上一步声明时也尝试过,

caption = Regex.Match(response, pattern).Groups[1].Value.Replace("\n", Environment.NewLine);

也没有用。

但是,当我手动尝试输入这样的字符串时:

string test = "We all know you can never have too many yoga pants!! Today's giveaway is with my fav @aloyoga \ud83d\ude0d \ud83c\udf81\ud83d\udcaa\ud83c\udffcI am honestly so proud of everyone who has been participating in the #JenSelterChallenge.. I have been overwhelmed by the level of commitment, progress, and positivity over the last couple of weeks. Seeing your photos and captions puts a huge smile on my face everyday. Thank you guys for making it such a success and for those who haven't joined yet, it's not too late! Congrats to the winners of WEEK 3\u2014 I will DM you all this weekend!! \ud83d\ude03 \n@Vicfitness_\n@Bodyroxxfit\n@Krvstah\n@Lvlelissa3\n@ThisIsNaila \n@X_i_a_r_a_\n@Btrevellini\n@Nicolesfitjourney_ \n#Seltering";
test.Replace("\n", Environment.NewLine);

它工作正常。但是我不确定当我对字符串进行硬编码和正常获取时有什么不同。是一模一样的字符串,我自己调试查过了。有什么我不知道的吗?

最佳答案

当你执行“\n”时,它会变成单个字符 0x0A。看起来您真正想要的是彼此相邻的两个字符“\”和“n”。

在你的替换字符串前面放一个@,它会停止将\n翻译成0x0A

caption = caption.Replace(@"\n", Environment.NewLine);

你也可以通过转义斜杠来做到这一点

caption = caption.Replace("\\n", Environment.NewLine);

关于c# - 替换在某些情况下不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37869427/

相关文章:

c# - JsonConvert.DeserializeObject,索引超出数组范围

javascript - 如何将javascript中的数字数组转换为字符串?

java 将特殊字符替换为文本

java - 是否可以在 Java 中使用正则表达式在 + 和 - 之间切换?

linux - 如何使用 sed 用反斜杠替换字符串模式

c# - 寻找错误的命名空间?

c# - Autofac 枚举不适用于类型或模块的多个注册

c# - Azure队列在DeleteMessage上抛出异常

java - 如何切换字符串中的字母

python - 如何在python中添加像 '1 hour and 5 second '这样的字符串的当前日期