我想知道是否有人知道如何遍历字符串中的每个字符,然后将每个字符添加到一个新的字符串中?这只是一个非常基本的示例,我可以添加ToUpper
和ToLower
验证等。
string foo = "hello world", bar = string.Empty;
foreach(char c in foo){
bar += c;
}
使用 StringBuilder
:string foo = "hello world";
StringBuilder bar = new StringBuilder();
foreach (char c in foo)
{
bar.Append(c);
}
以下是 String
类的签名:[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
StringBuilder
非常适合大量字符串拼接... - Alexfoo[5]
。 - Alexvar output = ""; // or use StringBuilder
foreach(char c in text)
{
output += c; // if or do with c what you need
}
你需要的是这个吗?
字符串是 IEnumerable<char>
string source = "foo"; string copy = source;
- Marc