如何判断一个字符串中包含的是同一个字符?

liuzhisheng 2009-03-04 03:21:45
如题,像“aaaaaaaaaaaaa“,“111111111111”,“%%%%%%%%%%%%”等都分别包含同一个字符串a,1,%,希望有一个高效的算法,最好是正则表达式。

谢谢
...全文
131 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
-过客- 2009-03-05
  • 打赏
  • 举报
回复
楼主这种需求,正则肯定谈不上高效了,应用正则要先加载正则引擎,为了这样一个简单的需求,完全没必要用大炮打蚊子
正则无论哪种引擎,其实现原理都是有穷状态机,因为这个需求简单,完全可以自己写一个状态机

bool flag = true;
if (yourStr.Length == 0)
{
richTextBox2.Text = "空字符串";
}
else
{
char firstChar = yourStr[0];
foreach (char c in yourStr)
{
if (firstChar != c)
{
flag = false;
break;
}
}
}
if (flag)
{
richTextBox2.Text = "全一样";
}
else
{
richTextBox2.Text = "不全一样";
}


我对算法一窍不通,上面的写法,相同则遍历一遍,不同则不用全部遍历,效率上应该还过得去,但估计不是最优做法

PS1:^(.)\1+$少考虑了只有一个字符的情况
PS2: 谈到效率,Replace就不用考虑了
睡神在睡觉 2009-03-04
  • 打赏
  • 举报
回复
public static bool Check_Str(string str)
{
for(int i=0;i<str.length;i++)
{
if(str[i]!=str[0])
return false;
}
return true;
}
surlew 2009-03-04
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 ShinNakoruru 的回复:]
str.Replace(str[0].ToString(),"")==""

这种方法也可以~~
[/Quote]

这个方法经典!
天乐 2009-03-04
  • 打赏
  • 举报
回复
欣赏正则秀
cppfaq 2009-03-04
  • 打赏
  • 举报
回复
Regex reg=new Regex(@"^(.)\1+$");
止戈而立 2009-03-04
  • 打赏
  • 举报
回复
Regex reg=new Regex(@"^(.)\1+$");
if(reg.IsMatch("aaaaaaaa"))//匹配
猿敲月下码 2009-03-04
  • 打赏
  • 举报
回复
import java.util.regex.*;

public class MyRegex {
public static void main(String[] args) {
String s="1111111111111111";
String temp=s.substring(0, 1);//取第一个字符
int count=0;
Matcher m=Pattern.compile(temp).matcher(s);
while(m.find())
{
count++;
}
if(count==s.length())
System.out.println("全部一样");
else
System.out.println("不一样");
}
}
ShinNakoruru 2009-03-04
  • 打赏
  • 举报
回复
str.Replace(str[0].ToString(),"")==""

这种方法也可以~~
indeep 2009-03-04
  • 打赏
  • 举报
回复
我也来学习一下
xing020010 2009-03-04
  • 打赏
  • 举报
回复
(.)+
JaggerLee 2009-03-04
  • 打赏
  • 举报
回复
(.)\1+
csjtxy 2009-03-04
  • 打赏
  • 举报
回复
就用正则表达式呀,建议楼主去学学正则表达式。

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧