欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

c#对字符串操作的技巧小结

程序员文章站 2023-12-12 15:35:04
字符串是由类定义的,如下1 public sealed class string : icomparable, icloneable, iconvertible, icom...

字符串是由类定义的,如下
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这个集合操作,那么把它拿来解决这个问题如下:
复制代码 代码如下:

   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的信息替换原信息。如果不匹配,使用原字符串。
如果问题敬请指出。

上一篇:

下一篇: