如何实现字符逐字符遍历?
当我应用 IEnumerator 并执行 MoverNext() 时,它会像这样遍历 C 风格 'a' 'p' 'p' 'l' 'e' '\o'
直到找到空字符?我以为它会返回整个字符串。这里的枚举是如何工作的?
string ar = "apple";
IEnumerator enu = ar.GetEnumerator();
while (enu.MoveNext())
{
Console.WriteLine(enu.Current);
}
我得到的输出为
a
p
p
l
e
When i apply IEnumerator and perform MoverNext() will it traverse like
C-Style 'a' 'p' 'p' 'l' 'e' '\o'
until it finds null character?I thought it would return the entire string.How does the enumeration work here?
string ar = "apple";
IEnumerator enu = ar.GetEnumerator();
while (enu.MoveNext())
{
Console.WriteLine(enu.Current);
}
I get output as
a
p
p
l
e
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
C# 中的字符串不是以 null 结尾的。或者更确切地说,字符串以 null 结尾的事实是对用户隐藏的实现细节。字符串“apple”有五个字符,而不是六个。你要求看这五个角色,我们就把他们全部展示给你。没有第六个空字符。
Strings are not null-terminated in C#. Or, rather, the fact that strings are null-terminated is an implementation detail that is hidden from the user. The string "apple" has five characters, not six. You ask to see those five characters, we show all of them to you. There is no sixth null character.
空字符不是 CLR / .Net 字符串的固有部分,因此不会显示在枚举中。枚举字符串将按顺序返回字符串的字符
The null character is not an inherent part of a CLR / .Net string and hence will not show up in the enumeration. Enumerating a string will return the characters of the string in order
枚举器每次迭代(
MoveNext()
调用)返回底层容器的每个元素。在这种情况下,您的容器是一个string
,其元素类型是char
,因此枚举器每次迭代都会返回一个字符。此外,字符串的长度由
string
类型得知,枚举器实现可以利用该类型来了解何时终止其遍历。An enumerator returns each element of the underlying container per iteration (
MoveNext()
call). In this case, your container is astring
and its element type ischar
, so the enumerator will return a character per each iteration.Also, the length of the string is known by the
string
type, which may be leveraged by the enumerator implementation to know when to terminate its traversal.C# 字符串的存储方式与 COM 字符串类似,有一个长度字段和一个 unicode 字符列表。因此不需要终结者。它使用更多的内存(多 2 个字节),但字符串本身可以保存空值,没有任何问题。
另一种解析字符串的方法与您的代码使用相同的功能,更像 C#:
C# strings are stored like COM strings, a length field and a list of unicode chars. Therefore there's no need of a terminator. It uses a bit more memory (2 bytes more) but the strings themselves can hold nulls without any issues.
Another way to parse strings that uses the same functionality as your code only is more C#-like is: