TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# CharEnumerator Type: String GetEnumerator, While Loop

This C# program uses the CharEnumerator type. It loops over a string.

CharEnumerator is used to loop over a string.

We test the CharEnumerator type. The CharEnumerator is acquired through the GetEnumerator method on the string type. It offers few advantages over other constructs.

Example. To start, this program declares a string literal and then calls the GetEnumerator method. We then use a while-loop to repeatedly call the MoveNext method, which returns a bool. The Current property returns the current character.

String LiteralWhile

C# program that uses CharEnumerator

using System;

class Program
{
    static void Main()
    {
	// Input string.
	string val = "dotnet";
	// Get enumerator.
	CharEnumerator e = val.GetEnumerator();
	// Use in loop.
	while (e.MoveNext())
	{
	    char c = e.Current;
	    Console.WriteLine(c);
	}
    }
}

Output

d
o
t
n
e
t

Performance. You should be aware of the other ways you can loop through strings, including the foreach and for-loops. I wondered if the CharEnumerator version of the string loop had any advantage over these methods.

Loop Over String Chars

Benchmark: This benchmark tests a loop over a short four-character string using the CharEnumerator-style code, and the foreach-style code.

C# program that benchmarks CharEnumerator

using System;
using System.Diagnostics;

class Program
{
    const int _max = 100000000;
    static void Main()
    {
	var s1 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    Method1("test");
	}
	s1.Stop();
	var s2 = Stopwatch.StartNew();
	for (int i = 0; i < _max; i++)
	{
	    Method2("test");
	}
	s2.Stop();
	Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
	    _max).ToString("0.00 ns"));
	Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
	    _max).ToString("0.00 ns"));
	Console.Read();
    }

    static int Method1(string val)
    {
	int res = 0;
	CharEnumerator c = val.GetEnumerator();
	while (c.MoveNext())
	{
	    res += (int)c.Current;
	}
	return res;
    }

    static int Method2(string val)
    {
	int res = 0;
	foreach (char c in val)
	{
	    res += (int)c;
	}
	return res;
    }
}

Results

33.33 ns    CharEnumerator
 4.79 ns    foreach

The CharEnumerator method of looping over all the characters in a string is much slower than the foreach method. There is a significant drawback to ever using the CharEnumerator in a loop on a string in the C# language.

Discussion. Using CharEnumerator directly (as shown) is not appropriate. But if you have code that requires a reference of type IEnumerator or IEnumerator<char>, you can use the CharEnumerator through those types.

Note: CharEnumerator implements those interfaces. But this is not something that will occur in many programs.

Summary. The CharEnumerator type presents an implementation of an enumerator for the string type. To get a CharEnumerator, call GetEnumerator on a string instance. The performance of CharEnumerator is much worse than looping.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf