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

时间:2016-06-16 21:12:41

标签: c# string replace

我有以下字符串。

  

我们都知道你永远不会有太多瑜伽裤!今天的赠品是我最喜欢的@aloyoga \ ud83d \ ude0d \ ud83c \ udf81 \ ud83d \ udcaa \ ud83c \ udffc我老实说为所有参与#JenSelterChallenge的人感到骄傲。我被这个人所震撼过去几周的承诺,进步和积极性水平。看到你的照片和标题每天都会给我的脸上带来一丝笑容。谢谢你们让它取得如此成功,对于那些尚未加入的人来说,现在还为时已晚!恭喜WEEK 3 \ u2014的获奖者,我将在本周末为您提供所有内容! \ 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);

工作正常。但是,当我对字符串进行硬编码以及正常运行时,我不确定有什么不同。它是完全相同的字符串,我自己通过调试来检查它。有什么我不知道的吗?

2 个答案:

答案 0 :(得分:7)

当您执行转换为单个字符0x0A的“\ n”时。你真正想要的是两个字符“\”和“n”彼此相邻。

@放在替换字符串前面,它会停止将\n翻译为0x0A

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

您也可以通过转义斜杠

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

答案 1 :(得分:0)

如果你做caption.Replace("\\n", Environment.NewLine);吗?

看起来您的字符串不包含换行符'\ n',而是由反斜杠后跟字符n组成的字符串。