这些消息完全不需要担心其间的变化或simbols,现在我只是在寻找一种有效的方法来检查下面的消息。
我有一条消息:
string msg = "This is a small message !";
我想检查该消息是否在同一个字符串中重复发送,如下所示:
string msg = "This is a small message !This is a small message !";
或:
string msg = "This is a small message !This is a small message !This is a small message !";
或:
string msg = "This is a small message !This is a small message !This is a small message !This is a small message !This is a small message !";
我有一个LinkedList<string>
存储收到的最后3条消息,以及最后3条消息我希望与当前消息匹配,以查看它是否等于当前存储消息之一或重复任何。
foreach (string item in myListOfMessages)
{
if (string.Equals(msg, item))
{
// the message matchs one of the stored messages
}
else if (msg.Lenght == (item.Lenght * 2) && string.Equals(msg, string.Concat(item, "", item)))
{
// the message is a repetition, and ofc only works when some one sends the message twice in the same string
}
}
就像我在示例中所示,重复可能非常大,我也不确定上面介绍的方法是否是我需要的最佳方法。这是第一个出现在我脑海中的想法,但很快我意识到它会以这种方式产生更多的工作。
答案 0 :(得分:2)
Linq救援:
string msg = "This is a small message !";
string otherMsg = "This is a small message !This is a small message !This is a small message !This is a small message !This is a small message !";
bool isRepeated = Enumerable.Range(0, otherMsg.Length / msg.Length)
.Select(i => otherMsg.Substring(i * msg.Length, msg.Length))
.All( x => x == msg);
这种方法基本上采用第一条消息长度的子字符串,并将每个块与原始消息进行比较。
包含一些预先检查的方法:
public bool IsRepeated(string msg, string otherMsg)
{
if (otherMsg.Length < msg.Length || otherMsg.Length % msg.Length != 0)
return false;
bool isRepeated = Enumerable.Range(0, otherMsg.Length / msg.Length)
.Select(i => otherMsg.Substring(i * msg.Length, msg.Length))
.All(x => x == msg);
return isRepeated;
}
修改强>
以上方法将生成不必要的字符串,这些字符串必须是gc'ed - 一种更有效,更快速的解决方案:
public bool IsRepeated(string msg, string otherMsg)
{
if (otherMsg.Length < msg.Length || otherMsg.Length % msg.Length != 0)
return false;
for (int i = 0; i < otherMsg.Length; i++)
{
if (otherMsg[i] != msg[i % msg.Length])
return false;
}
return true;
}
答案 1 :(得分:1)
您可以尝试使用正则表达式
string msg = "This is a small message !";
string Input = "This is a small message !This is a small message !";
System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(msg);
System.Text.RegularExpressions.MatchCollection Matches = r.Matches(Input);
int Count = Matches.Count; //Count = 2
答案 2 :(得分:1)
private int countRepeats(string msg, string item)
{
if(string.Replace(msg, item).Length > 0)
return 0;
return msg.Length / item.Length;
}
答案 3 :(得分:1)
static void Main(string[] args)
{
string msg = "This is a small message !This is a small message !This is a small message !";
string substring = "This is a small message !";
string[] split = msg.Split(new string[] { substring }, StringSplitOptions.None);
Console.WriteLine(split.Length - 1);
foreach (string splitPart in split)
{
if (!String.IsNullOrEmpty(splitPart))
Console.WriteLine("Extra info");
}
}