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.
Asked
Active
Viewed 1.2e+01k times
41

pb2q
- 58,613
- 19
- 146
- 147

user1290653
- 775
- 3
- 11
- 23
-
I'm sure you're just after the mechanics of your question and probably not the output, but since strings are immutable, your output is the same simply with assignment: `string source = "foo"; string copy = source;` – Marc Apr 07 '12 at 22:29
2 Answers
78
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

Alex
- 34,899
- 5
- 77
- 90
-
Keep in mind that you don't want to do this with large strings as performance will be horrible. – ChaosPandion Apr 07 '12 at 22:27
-
@ChaosPandion agreed, `StringBuilder` is ideal for significant amounts of concatenations ... – Alex Apr 07 '12 at 22:29
-
or better use array (you can go back/forth inspect where needed too), IndexOf if you need to search, string constructor if you know the final array size... – NSGaga-mostly-inactive Apr 07 '12 at 22:43
-
@NSGaga a string already is and exposes an iterator ... try doing `foo[5]` – Alex Apr 07 '12 at 22:45
-
1what I'm saying exactly - don't enumerate use [] etc. we misunderstood – NSGaga-mostly-inactive Apr 07 '12 at 22:53
5
var output = ""; // or use StringBuilder
foreach(char c in text)
{
output += c; // if or do with c what you need
}
...is that what you needed?
string is IEnumerable<char>

NSGaga-mostly-inactive
- 14,052
- 3
- 41
- 51