查看字符串中的每个字符

41

我想知道是否有人知道如何遍历字符串中的每个字符,然后将每个字符添加到一个新的字符串中?这只是一个非常基本的示例,我可以添加ToUpperToLower验证等。


我相信你只是想了解问题的机制,而不是输出结果,但由于字符串是不可变的,所以你的输出结果只需要简单的赋值即可:string source = "foo"; string copy = source; - Marc
2个回答

78
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


请记住,不要对大字符串执行此操作,因为性能会非常差。 - ChaosPandion
@ChaosPandion 同意,StringBuilder非常适合大量字符串拼接... - Alex
或者更好的做法是使用数组(你可以来回检查需要的地方),如果需要搜索则使用IndexOf,如果知道最终数组大小,则使用字符串构造函数... - NSGaga-mostly-inactive
@NSGaga 一个字符串已经存在并公开了一个迭代器...尝试执行 foo[5] - Alex
1
我们误解了,确切地说我是指不要列举使用[]等。 - NSGaga-mostly-inactive

5
var output = ""; // or use StringBuilder
foreach(char c in text)
{
     output += c; // if or do with c what you need
}

你需要的是这个吗?
字符串是 IEnumerable<char>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接