使用新行查找并替换ASCII字符

时间:2012-05-24 18:50:38

标签: c# .net 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();
}

这不会添加新行,并且字符串全部保留在一行中。我不确定这里的问题是什么。我也试过这个,但结果相同:

n.Replace(replaceMe, "\n");

有什么建议吗?

2 个答案:

答案 0 :(得分:10)

char.ConvertFromUtf32虽然正确,但不是基于其ASCII数值读取字符的最简单方法。 (ConvertFromUtf32主要用于位于BMP之外的Unicode代码点,这会导致代理对。这不是您在英语或大多数现代语言中遇到的情况。)相反,您应该使用{ {1}}。

(char)

当然,您可以在代码中将所需字符定义为字符串:char c = (char)187; string replaceMe = c.ToString();

您的"»"将简化为:

Replace

最后,在技术层面上,ASCII仅涵盖其值在0-127范围内的字符。字符187不是ASCII;但是,它对应于ISO 8859-1,Windows-1252, Unicode中的n.Replace("»", "\n"); ,它们是目前使用最流行的编码。

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

No newlines?

请注意,»序列实际执行表示新行,尽管显示为文字。您可以从多行显示中检查(通过单击放大镜):

Newlines!

答案 1 :(得分:0)

StringBuilder.Replace会返回一个新的StringBuilder,其中包含所做的更改。奇怪,我知道,但这应该有效:

StringBuilder replaced = n.Replace(replaceMe, Environment.NewLine);

return replaced.ToString();