English 中文(简体)
用新行查找并替换 ASCII 字符
原标题:Find and replace ASCII character with a new line

我试图在字符串中找到每一个 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, "
");

有什么建议吗?

最佳回答

char. ConvertfromUtf32 ,虽然是正确的,但并不是根据 ASCII 的数值阅读字符的最简单的方式。 ( ConvertformUtf32 主要是针对位于 BMP 外的 Unicode 代码点,从而产生代孕配对。 这不是你用英语或大多数现代语言遇到的东西。)相反,你应该使用 (char) 来投出它。

char c = (char)187;
string replaceMe = c.ToString();

当然,您可以在代码中将带有所需字符的字符串定义为字面文字 : "\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\可以\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

您的 replace 将简化为:

n.Replace("»", "
");

最后,在技术层面, ASCII 仅涵盖值在 0-127 范围内的字符。 字符 187 不是 ASCII; 但是, 它相当于ISO 8859-1、 Windows-1252、 Unicode中的 < code > 。 这些字符是迄今最常用的编码。

< 坚固 > 编辑 < / 坚固 > : 我刚刚测试了您原来的代码, 发现它实际上有效 。 您确定结果仍停留在一条线上吗? 这也许与调试器在单行视图中设置字符串的方式有问题 :

""https://i.sstatic.net/S41X8.png" alt="没有新线?"/"

Note that the sequences actually do represent newlines, despite being displayed as literals. You can check this from the multi-line display (by clicking on the magnifying glass):

https://i.sstatic.net/xDYHf.png" alt=“Newlines!”/> https://i.sstatic.net/xDYHf.png" alt=“Newlines!”/>

问题回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...