Loop Through Each Character In A String In C#
Code snippet for how to Loop Through Each Character In A String In C# with sample and detail explanation
In this article, we’ll be exploring how to loop through each character in a string in C#. This is a fundamental concept in programming that can often be overlooked but is crucial in developing various applications and software.
Code snippet for Character Looping in a String
In C#, looping through each character in a string can be achieved with a simple foreach loop. Here is a simple code snippet that demonstrates this:
string str = "Hello World";
foreach (char c in str)
{
System.Console.WriteLine(c);
}
Code Explanation for Character Looping in a String
Let’s break down the code step by step to understand how we loop through each character in a string in C#.
- We first declare a string
str
and assign it the value “Hello World”.
string str = "Hello World";
- Next, we initiate a foreach loop. The foreach loop is a control flow statement for traversing items in a collection. In our case, the collection is the string
str
.
foreach (char c in str)
- Within the foreach loop, we have a
System.Console.WriteLine(c);
statement. This command prints out the characters of the stringstr
one by one. Herec
is the variable that holds the current character during each iteration of the loop.
{
System.Console.WriteLine(c);
}
In C#, a string is essentially a sequential read-only collection of char
data type. Hence, we can use a foreach loop to go through each item which, in this case, is a character. This small but mighty piece of code represents one of the many powerful actions you can perform on strings in C#!