如何获取 C# 中所有可打印字符的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/887377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get a list of all the printable characters in C#?
提问by Phil Bennett
I'd like to be able to get a char array of all the printable characters in C#, does anybody know how to do this?
我希望能够在 C# 中获得所有可打印字符的字符数组,有人知道怎么做吗?
edit:
编辑:
By printable I mean the visible European characters, so yes, umlauts, tildes, accents etc.
我所说的可打印是指可见的欧洲字符,所以是的,元音、波浪符、重音等。
采纳答案by Fredrik M?rk
This will give you a list with all characters that are not considered control characters:
这将为您提供一个列表,其中包含不被视为控制字符的所有字符:
List<Char> printableChars = new List<char>();
for (int i = char.MinValue; i <= char.MaxValue; i++)
{
char c = Convert.ToChar(i);
if (!char.IsControl(c))
{
printableChars.Add(c);
}
}
You may want to investigate the other Char.IsXxxxmethods to find a combination that suits your requirements.
您可能想要调查其他Char.IsXxxx方法以找到适合您要求的组合。
回答by Noldorin
A LINQ solution (based on Fredrik M?rk's):
一个 LINQ 解决方案(基于 Fredrik M?rk 的):
Enumerable.Range(char.MinValue, char.MaxValue).Select(c => (char)c).Where(
c => !char.IsControl(c)).ToArray();
回答by Jon Skeet
Here's a LINQ version of Fredrik's solution. Note that Enumerable.Range
yields an IEnumerable<int>
so you have to convert to chars first. Cast<char>
would have worked in 3.5SP0 I believe, but as of 3.5SP1 you have to do a "proper" conversion:
这是 Fredrik 解决方案的 LINQ 版本。请注意,会Enumerable.Range
产生一个,IEnumerable<int>
因此您必须先转换为字符。Cast<char>
我相信会在 3.5SP0 中工作,但是从 3.5SP1 开始,您必须进行“正确”转换:
var chars = Enumerable.Range(0, char.MaxValue+1)
.Select(i => (char) i)
.Where(c => !char.IsControl(c))
.ToArray();
I've created the result as an array as that's what the question asked for - it's not necessarily the best idea though. It depends on the use case.
我已经将结果创建为一个数组,因为这就是问题所要求的 - 但这不一定是最好的主意。这取决于用例。
Note that this also doesn't consider full Unicode characters, only those in the basic multilingual plane. I don't know what it returns for high/low surrogates, but it's worth at least knowing that a single char
doesn't really let you represent everything :(
请注意,这也不考虑完整的 Unicode 字符,只考虑基本多语言平面中的字符。我不知道高/低代理的回报是什么,但至少值得知道一个单一的char
并不能真正让你代表一切:(
回答by Michael Murphy
I know ASCII wasn't specifically requested but this is a quick way to get a list of all the printable ASCII characters.
我知道 ASCII 没有特别要求,但这是获取所有可打印 ASCII 字符列表的快速方法。
for (Int32 i = 0x20; i <= 0x7e; i++)
{
printableChars.Add(Convert.ToChar(i));
}
See this ASCII table.
请参阅此ASCII 表。
回答by Artem Y
public bool IsPrintableASCII(char c)
{
return c >= '\x20' && c <= '\x7e';
}