zoukankan      html  css  js  c++  java
  • c# 过滤字符串中的重复字符

    有字符串"a,s,d,v,a,v",如果想去除其中重复的字符,怎么做?

    下面是一个方法,用Hashtable来记录唯一字符,排除重复字符,仅供参考。

    1.过滤方法:

    public class OperationString
        {
            /// <summary>
            /// 过滤字符串中的重复字符
            /// </summary>
            /// <param name="str">要过滤的字符串</param>
            /// <returns>返回过滤后的字符串</returns>
            public string FilterRepetitionChar(string sourceStr)
            {
                string returnStr = string.Empty;
                string[] strList = sourceStr.Split(',');
                Hashtable ht = new Hashtable();
                foreach (string strChar in strList)
                {
                    if (!ht.ContainsKey(strChar))
                    {
                        ht.Add(strChar, strChar);//这里让ht的key和value值相等,不影响下面的程序
                        returnStr += strChar + ",";//字符以逗号分隔
                    }
                }
                returnStr = returnStr.Trim(',');//去掉最后一个逗号
                return returnStr;
            }
        }

    2.程序入口:

    class Program
        {
            static void Main(string[] args)
            {
                string sourceString = "a,b,c,d,a,b";
                string newString = string.Empty;
    
                OperationString os = new OperationString();
                newString = os.FilterRepetitionChar(sourceString);
    
                Console.WriteLine("过滤前的字符串:" + sourceString);
                Console.WriteLine("----------------------------------");
                Console.WriteLine("过滤后的字符串:" + newString);
    
                Console.ReadKey();
            }
        }

    3.运行结果:

    过滤前的字符串:a,b,c,d,a,b

    ----------------------------------
    过滤的字符串:a,b,c,d
     
     
  • 相关阅读:
    JavaScript -- BATweb笔试面试
    1--html属性
    0--node安装
    1-- express
    lsof命令
    1--字符串和数组的指向问题
    19--复杂链表的复制。
    18--二叉树中和为某一值的路径
    剑指offer——64和为s的数字
    剑指offer——04二维数组中的查找
  • 原文地址:https://www.cnblogs.com/qk2014/p/4448732.html
Copyright © 2011-2022 走看看