不断积累,必然飞跃,突破随之!

相信自己,开拓生活!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

除去字符串中不相临的重复的字符 aabcad 得 aabcd

Posted on 2014-07-14 22:09  Tangyuan2017  阅读(933)  评论(0编辑  收藏  举报

假设有一个字符串aabcad,请编写一段程序,去掉字符串中不相邻的重复字符。即上述字串处理之后结果是为:aabcd;

分析,重点考查 char 与int 的隐式转换。程序如下:

 static void Main(string[] args)
        {
            //除去不临的重复字符

            Console.WriteLine("aabcad");
            Console.WriteLine("aabcd");

            string str = "aabcad";
            char[] source = str.ToArray();

            string result = "";

            for (int i = 0; i < source.Length; i++)
            {
                if (i == 0)
                {
                    result = result + source[i].ToString();
                }
                else
                {
                    if (source[i] != source[i - 1] && source[i] != (source[i - 1] + 1) && result.Contains(source[i]))
                        continue;
                    else
                        result = result + source[i].ToString();
                }
            }
            Console.WriteLine(result);

            Console.ReadLine();
        }