我正在尝试查找字符串中每个出现的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中的»,它们是迄今为止最流行的编码。

编辑:我刚刚测试了您的原始代码,发现它确实有效。您确定结果保持一行吗?调试器在单行视图中呈现字符串的方式可能是一个问题:



请注意,尽管\r\n序列实际上显示为换行符,但它们显示为文字。您可以在多行显示中进行检查(通过单击放大镜):

07-25 23:59
查看更多