欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#對字符串操作的技巧小結(jié)

 更新時間:2013年04月15日 10:45:08   作者:  
c#對字符串操作的技巧小結(jié),需要的朋友可以參考一下

字符串是由類定義的,如下
1 public sealed class String : IComparable, ICloneable, IConvertible, IComparable<string>, IEnumerable<char>, IEnumerable, IEquatable<string>
注意它從接口IEnumerable<char>派生,那么如果想得到所有單個字符,那就簡單了,
1 List<char> chars = s.ToList();
如果要對字符串進行統(tǒng)計,那也很簡單:
1 int cn = s.Count(itm => itm.Equals('{'));
如果要對字符串反轉(zhuǎn),如下:
1 new string(s.Reverse().ToArray());
如果對字符串遍歷,那么使用擴展方法ForEach就可以了。
現(xiàn)在有一個需求 ,對一個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.
所以如下代碼其實是構(gòu)造了兩個字符串:
1 string st = "Hello,world";
2 st = "Hello,world2";
回到那個問題,我想一個很簡單的方法是先構(gòu)造一個List<string>,然后對原字符串遍歷 ,滿足條件的修改后加入新的list,不滿足的直接加入。這種方法很簡單原始,效率也是最高的。Linq里面有UNION這個關(guān)鍵字,sql里面也有UNION這個集合操作,那么把它拿來解決這個問題如下:
復(fù)制代碼 代碼如下:

   private List<String> StringCleanUp(List<string> input)
         {
             Regex reg = new Regex(@"\<(\w+)\>(\w+?)\</\1\>", RegexOptions.Singleline);
  
             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;
         }

以上是用正則表達式進行匹配,如果匹配,用匹配的組2的信息替換原信息。如果不匹配,使用原字符串。
如果問題敬請指出。

相關(guān)文章

最新評論