字符串是由類定義的,如下 1 public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string> 注意它從接口IEnumerable<char>派生,那么如果想得到所有單個字符,那就簡單了, 1 List<char> chars = s.ToList(); 如果要對字符串進行統計,那也很簡單: 1 int cn = s.Count(itm => itm.Equals('{')); 如果要對字符串反轉,如下: 1 new string(s.Reverse().ToArray()); 如果對字符串遍歷,那么使用擴展方法ForEach就可以了。 現在有一個需求 ,對一個list的字符串,我想對滿足某些條件的進行替換,不滿足條件的保留下來。問題來了,在forach的時候不能對字符串本身修改。因為msdn有如下的描述: A String object is called immutable (read-only) because its value cannot be modified once it has been created. Methods that appear to modify a String object actually return a new String object that contains the modification. 所以如下代碼其實是構造了兩個字符串: 1 string st = "Hello,world"; 2 st = "Hello,world2"; 回到那個問題,我想一個很簡單的方法是先構造一個List<string>,然后對原字符串遍歷 ,滿足條件的修改后加入新的list,不滿足的直接加入。這種方法很簡單原始,效率也是最高的。Linq里面有UNION這個關鍵字,sql里面也有UNION這個集合操作,那么把它拿來解決這個問題如下:
var matchItem = ( from c in input where reg.IsMatch(c) select reg.Replace(c, matchEvaluator) ).Union( from c in input where !reg.IsMatch(c) select c );
return matchItem.ToList<string>(); }
private string matchEvaluator(Match m) { return m.Groups[2].Value; }