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

时间:2021-12-21 14:11:41

假设有一个字符串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();
}