用下面这个正则来匹配
(.)\1+
不过这个缺点是只能匹配连续的字符,比如说一个字母d的话就匹配不出来
代码如下:只考虑功能实现。
string str = "AAABBBFFFFFAAAFGCDRT";
string result1 = string.Empty, result2 = string.Empty;
int l = str.Length, k = 1;
for (int i = 0; i < l; i++)
{
if (i + 1 < l && str[i].ToString() == str[i + 1].ToString())
{
for (int j = i; j < l; j++)
{
if (j + 1 < l && str[j].ToString() == str[j + 1].ToString())
k++;//找出相同的字符,注意k的默认值
else
break;
}
result1 += str[i].ToString() + k.ToString();
i += k - 1;
k = 1;
}
else {
result1 += str[i].ToString() + "1";
}
}
MatchCollection mc = Regex.Matches(result1, "[A-Z]");
MatchCollection mc1 = Regex.Matches(result1, "[1-9]");
int m = 0;
if (mc.Count <= mc1.Count) m = mc.Count; else m = mc1.Count;
for (int m1 = 0; m1 < m; m1++) {
for (int m2 = 0; m2 < int.Parse(mc1[m1].Value); m2++)
{
result2 += mc[m1];
}
}
添加命名空间 using System.Text.RegularExpressions;
直接递归算法,很简单的噢:)
功能一:字符串:"AAABBBFFFFFAAA“,编程将其转换为'A3B3F6A3'。
protected string shuyishu(string var) {
int num=0;
if (var.Length > 0) {
string firststr = var[0].ToString();
num++;
for (int i = 1; i < var.Length; i++)
{
if (var[i].ToString() == firststr)
num++;
else
break;
}
return firststr + num.ToString()+shuyishu(var.Substring(num));
}
else
return "";
}
功能二,直接用楼上的吧,没法再简单了