我正在尝试查找字符串中每次出现的 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();
}
这不会添加新行,所有字符串都保留在一行中。我不确定这里有什么问题。我也试过这个,但结果相同:
n.Replace(replaceMe, "\n");
有什么建议吗?
最佳答案
char.ConvertFromUtf32
虽然正确,但并不是根据 ASCII 数值读取字符的最简单方法。 (ConvertFromUtf32
主要用于位于 BMP 之外的 Unicode 代码点,这会导致代理项对。这不是您在英语或大多数现代语言中遇到的事情。)相反,您应该只投它使用 (char)
。
char c = (char)187;
string replaceMe = c.ToString();
当然,您可以在代码中将具有所需字符的字符串定义为文字:"»"
。
您的 Replace
将被简化为:
n.Replace("»", "\n");
最后,在技术层面上,ASCII 仅涵盖值在 0-127 范围内的字符。字符 187 不是 ASCII;但是,它对应于 ISO 8859-1、Windows-1252、和 Unicode 中的 »
,它们共同构成了当今最流行的编码。
编辑:我刚刚测试了您的原始代码,发现它确实有效。您确定结果保持在一行上吗?调试器在单行 View 中呈现字符串的方式可能存在问题:
请注意,\r\n
序列实际上确实 表示换行符,尽管显示为文字。您可以从多行显示中查看(通过单击放大镜):
关于c# - 查找并用新行替换 ASCII 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10743571/