- 大鱼炖火锅
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo_101201
{
class Program
{
static void Main(string[] args)
{
// string newstr = "";
Console.WriteLine("请输入字符串...");
string str = Console.ReadLine();
char[] a = str.ToCharArray();
string newstr = ""+a[0];
for (int i = 1; i < a.Length; i++)
{
if (a[i] != a[i - 1])
{
newstr = newstr + a[i];
}
}
Console.WriteLine(newstr);
}
}
}
- Chen
-
public static string getchar(string str)
{
List<char> list = new List<char>();
string sTmp = "";
char[] strArr = str.ToCharArray();
for (int i = 0; i < strArr.Length; i++)
{
list.Add(strArr[i]);
}
for (int j = 0; j < list.Count;)
{
if (list[j] == list[j + 1])
{
list.RemoveAt(j);
j--;
}
j++;
if (j == list.Count-1)
{
break;
}
}
foreach (char c in list)
{
sTmp += c.ToString();
}
return sTmp;
}
- 再也不做站长了
-
当字符串过长时使用楼上方法效率极差,使用正则表达式最简单:
string str = "asdasdaa bbasddawd;;aasd00011asda[[[]]]]";
str = Regex.Replace(str, @"(S)1+", "$1", RegexOptions.IgnoreCase);
Console.WriteLine(str);
- 阿里阿涅德
-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Answer
{
/// <summary>
/// 合并一个字符串中相邻的重复字符
/// </summary>
class StrCharCom
{
/// <summary>
/// 合并一个字符串中相邻的重复字符,返回一个char[]作为结果
/// </summary>
/// <param name="longStr">传入string类型参数</param>
/// <returns>返回合并了相邻重复字符的char数组</returns>
public static char[] CharCom(string longStr)
{
char[] shortChars = new char[longStr.Length];
shortChars[0] = longStr[0];
for (int i = 1,j = 0; i < longStr.Length; i++)
{
if (longStr[i] != shortChars[j])
{
shortChars[++j] = longStr[i];
}
}
return shortChars;
}
/*
* 重载了方法,传入参数为char[]
* */
/// <summary>
/// 合并一个字符串中相邻的重复字符,返回一个char[]作为结果
/// </summary>
/// <param name="longStr">传入char数组类型参数</param>
/// <returns>返回合并了相邻重复字符的char数组</returns>
public static char[] CharCom(char[] longStr)
{
char[] shortChars = new char[longStr.Length];
shortChars[0] = longStr[0];
for (int i = 1, j = 0; i < longStr.Length; i++)
{
if (longStr[i] != shortChars[j])
{
shortChars[++j] = longStr[i];
}
}
return shortChars;
}
/*
* 以下实现相同功能,不同的是返回值为string
*/
/// <summary>
/// 合并一个字符串中相邻的重复字符,返回一个string作为结果
/// </summary>
/// <param name="longStr">传入string类型参数</param>
/// <returns>返回合并了相邻重复字符的string</returns>
public static string CharComReStr(string longStr)
{
string shortStr = longStr[0].ToString();
for (int i = 1; i < longStr.Length; i++)
{
if (longStr[i] != longStr[i-1])
{
shortStr += longStr[i];
}
}
return shortStr;
}
/*
* 重载了方法,传入参数为char[]
* */
/// <summary>
/// 合并一个字符串中相邻的重复字符,返回一个string作为结果
/// </summary>
/// <param name="longStr">传入char[]类型参数</param>
/// <returns>返回合并了相邻重复字符的string</returns>
public static string CharComReStr(char[] longStr)
{
string shortStr = longStr[0].ToString();
for (int i = 1; i < longStr.Length; i++)
{
if (longStr[i] != longStr[i - 1])
{
shortStr += longStr[i];
}
}
return shortStr;
}
}
}