1

I am stuck on this question after doing a lot of research. I want to find the no. of occurrences of String in another String but needed very smart approach.

a = "ASAD"  str = "ASADASAD"  expect output:2
b = "AAA"   str2 = "AAAAAAAAAA"  expect output:8

For example, considers these two strings. On the first line, 'a' occurs twice in 'str' while on the second line if you see the whole combinations of b occurs 8 times in str2. How to address both these challenges at once in the same code. I have coded these two scenarios separately but I want to do it in a smart way so one code can deal with all possible combinations of input strings. Here is my code.

For Case 1

Type1 = (LongString.split(SmallStr, -1).length-1);

for Case 2

while (Index < SmallStr.length())
       {
           String tester = LongString.substring(Index);

           Counter = (tester.split(SmallStr,-1).length-1);
           ans= Counter + ans;
           lastIndex ++;
       }

           System.out.println(ans);
xingbin
  • 27,410
  • 9
  • 53
  • 103
Hsi S
  • 21
  • 3

1 Answers1

1

You might try something like this:

String myString = "ASADASAD"; // or "AAAAAAAAAA"
String stringToFind = "ASAD"; // or "AAA"

int offset = 0;
int count = 0;
while (offset < myString.length())
{
  int index = myString.indexOf(stringToFind, offset);
  if (index < 0)
    break;
  count++;
  offset = index + 1;
}
Robert Kock
  • 5,795
  • 1
  • 12
  • 20
  • Thank you so much! – Hsi S Apr 10 '18 at 14:25
  • But could you explain, how you performed the steps? :) – Hsi S Apr 10 '18 at 17:59
  • @HsiS: Simple iterate over the string searching for the desired one. You stop until the whole string is scanned or the desired one is no longer found. At every iteration, you start one position after the start of the previously found element. I hope it's clear now. – Robert Kock Apr 11 '18 at 07:42