How Char By Char Traversal is possible?
When i apply IEnumerator and perform MoverNext() will it traverse like
C-Style 'a' 'p' 'p' 'l' 'e' '\o'
until it f开发者_运维技巧inds 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
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.
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
An enumerator returns each element of the underlying container per iteration (MoveNext()
call). In this case, your container is a string
and its element type is char
, 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# 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:
string s="...";
foreach(char c in s)
Console.WriteLine(c);
精彩评论