And*_*est 2 .net c# string replace
我试图在字符串中找到每个ASCII字符的出现,并用新行替换它.这是我到目前为止:
public string parseText(string inTxt)
{
//String builder based on the string passed into the method
StringBuilder n = new StringBuilder(inTxt);
//Convert the ASCII character we're looking for to a string
string replaceMe = char.ConvertFromUtf32(187);
//Replace all occurences of string with a new line
n.Replace(replaceMe, Environment.NewLine);
//Convert our StringBuilder to a string and output it
return n.ToString();
}
Run Code Online (Sandbox Code Playgroud)
这不会添加新行,并且字符串全部保留在一行中.我不确定这里的问题是什么.我也试过这个,但结果相同:
n.Replace(replaceMe, "\n");
Run Code Online (Sandbox Code Playgroud)
有什么建议?
Dou*_*las 10
char.ConvertFromUtf32虽然正确,但不是基于其ASCII数值读取字符的最简单方法.(ConvertFromUtf32主要是用于那些躺在BMP,导致代理对外界的Unicode代码点.这是不是你的英语或最现代的语言遇到的问题.)相反,你应该使用只投它(char).
char c = (char)187;
string replaceMe = c.ToString();
Run Code Online (Sandbox Code Playgroud)
当然,您可以在代码中将所需字符的字符串定义为文字:"»".
Replace然后,您将简化为:
n.Replace("»", "\n");
Run Code Online (Sandbox Code Playgroud)
最后,在技术层面上,ASCII仅涵盖值在0-127范围内的字符.字符187不是ASCII; 但是,它对应»于ISO 8859-1,Windows-1252 和 Unicode,它们是迄今为止最常用的编码.
编辑:我刚刚测试了你的原始代码,发现它确实有效.你确定结果仍然在一行吗?调试器在单行视图中呈现字符串的方式可能存在问题:

请注意,\r\n序列实际上确实代表换行符,尽管显示为文字.您可以从多行显示中查看(通过单击放大镜):
