加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 05:44:00 所属栏目:百科 来源:网络整理
导读:字符串是由类定义的,如下 1 public sealed class String : IComparable,ICloneable,IConvertible,IComparablestring,IEnumerablechar,IEnumerable,IEquatablestring 注意它从接口IEnumerablechar派生,那么如果想得到所有单个字符,那就简单了, 1 Listchar

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

您可能感兴趣的文章:

  • 非常实用的C#字符串操作处理类StringHelper.cs
  • 总结的5个C#字符串操作方法分享
  • C#自定义的字符串操作增强类实例
  • C#中一些字符串操作的常用用法
  • C#减少垃圾回收压力的字符串操作详解

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读