Look at each character in a string

user1290653 picture user1290653 · Apr 8, 2012 · Viewed 89.7k times · Source

I was wondering if anyone knew how to look through a string at each character and then add each character to a new string? Just a really really basic example, I can add the ToUpper and ToLower validation and such.

Answer

xandercoded picture xandercoded · Apr 8, 2012
string foo = "hello world", bar = string.Empty;

foreach(char c in foo){
    bar += c;
}

Using StringBuilder:

string foo = "hello world";
StringBuilder bar = new StringBuilder();

foreach (char c in foo)
{
    bar.Append(c);
}

Below is the signature of the String class:

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class String : IComparable, 
    ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, 
    IEnumerable, IEquatable<string>

http://msdn.microsoft.com/en-us/library/system.string(v=vs.100).aspx