I'm trying to find an algorithm that takes an input from user (string1) and then takes another (string2) then counts How many string2 exist in string1. for example:
there is 2 # in string1 here
string1="##"
string2="#"
answer:2
there is 2 ## in string1:(1st one with the index of 0,1 and 2nd one with the index of 1,2)
string1="###"
string2="##"
answer=2
there is 3 ## in string1:(1st:index of 0,1 2nd:index of 1,2 3rd:index of 2,3)
string1="####"
string2="##"
answer=3
for counting # here we can simply do this:
string1.Length - string2.Length + 1
but I can only make the algorithm work for examples like these, while inputs can be anything. now i need an algorithm to do this for me. Here is ,y code that works for my inputs, but doesn't work for all inputs. for example if string2 was #a.
string string1 = "#abc##asd###12####";
string string2 = "##";
char[] str2 = string2.ToCharArray();
string[] str1 = string1.Split(str2);
string chars = "";
foreach (string s in str1)
foreach (char c in s)
chars += c;
//Result for chars are:a, b, c, a, s, d, 1, 2
string[] splits = string1.Split(chars.ToCharArray());
//Result for splits are:#, ##, ###, ####
int sum = 0;
for (int i = 0; i < splits.Length; i++)
{
if (splits[i].Length<string2.Length)
continue;
else
sum += splits[i].Length - string2.Length + 1;
}
Console.WriteLine(sum);
In my algorithm i seprated string1 by string2 characters and then count strings[] that was created by split method.
I already know that my algorithm is completely wrong, but I couldn't solve it anyway. I just put the code to show what i have tried.
if you write algorithm in your answer, that would be nice. I also have a little knowledge about lambda and linq so no problem if you could to this by lambda or linq or func or expression but explain about it.