TheDeveloperBlog.com

Home | Contact Us

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

<< Back to C-SHARP

C# Loop Over String Chars: Foreach, For

Loop over the characters in a string. Use a foreach-loop and a for-loop.
Loop over string chars. A loop iterates over individual string characters. It allows processing for each char. The foreach-loop and the for-loop are available for this purpose. The string indexer returns a char value.Indexer
Example. First, we look at 2 loops where we iterate over each char in a string. The string you loop over can be a string literal, a variable, or a constant. We use the foreach and for-loop.ForeachString For-LoopFor
C# program that uses foreach on string using System; class Program { static void Main() { const string s = "peace"; foreach (char c in s) { Console.WriteLine(c); } for (int i = 0; i < s.Length; i++) { Console.WriteLine(s[i]); } } } Output p e a c e p e a c e
For performance, it is sometimes easier for the JIT compiler to optimize the loops if you do not hoist the Length check outside of the for-loop. It is not often helpful to store the length in a local variable.
StringBuilder. For long inputs where we build up an output, a StringBuilder is important. It means we don't have to worry about hundreds or thousands of appends happening in edge cases.StringBuilderStringBuilder Performance
Regex. Sometimes using a loop is far more efficient than a Regex. Another advantage of loops is the ability to test each character and alert the user to special characters. Loops are imperative and offer more control.

However: Regular expressions offer more power in fewer characters. They are sometimes a better option.

Regex vs. LoopRegex
Summary. This simple method loops over each character in a string. The performance here is good because it only needs to make one pass over the string. Often, we use loops to test for special patterns.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


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