+ 2

How to check and print how many times '1001' is repeating in a binary string example. Input=10011001001 output=3.

1st Jan 2022, 8:39 PM
RORORZOSO
10 Answers
+ 8
A good function for this purpose is strstr(str1, str2). It returns a char pointer to the first occurrance of str2 that it finds within str1. After finding the first match, use the returned pointer+1 as str1 to start the next match. Use a while statement to count how many times it finds a match until the returned pointer is null.
1st Jan 2022, 9:00 PM
Brian
Brian - avatar
+ 5
RORORZOSO , have already done a try that you can show us? thanks!
1st Jan 2022, 8:51 PM
Lothar
Lothar - avatar
+ 3
Search lessons about KMP Algorithm.
1st Jan 2022, 9:10 PM
FanYu
FanYu - avatar
+ 2
Brian thank you also 👍
1st Jan 2022, 9:29 PM
RORORZOSO
3rd Jan 2022, 4:39 PM
Œ ㅤ
Œ ㅤ - avatar
+ 2
Jeff.C Yup, you *could* use the single ampersand bitwise operator but that'd only add to the execution time of the program. Here's the corrected expression: str[i] == '1' && str[i+1] == '0' && str[i+2] == '0' && str[i+3] == '1'
3rd Jan 2022, 4:44 PM
Œ ㅤ
Œ ㅤ - avatar
+ 1
fan yu that helps thanks a lot
1st Jan 2022, 9:28 PM
RORORZOSO
+ 1
Could you use: if (string[i]='1')&(string[i+1]='0')&(string[i+2]=0)&(string [i+3]=1): x+=1 else: //Not sure about my use of &, might have to check the syntax....
2nd Jan 2022, 4:34 AM
HungryTradie
HungryTradie - avatar
+ 1
G'day Quoi Runtime that seems to work nicely! What does the while do? Seems to me to only be true when num[max] == 1, so does it skip leading zeros? Does it also set max = len(num)-3? Do the remaining && get skipped if the first check is false? I know it's a pretty simple algorithm, but you mentioned that it may execute slowly, is there a much better way?
3rd Jan 2022, 9:32 PM
HungryTradie
HungryTradie - avatar
+ 1
Bonjour Jeff.C! The 'max' variable in my code is there so that my code doesn't read any garbage value once there aren't the required number of characters left to read. This way, the 'for' loop halts if there aren't four characters present between num[i] and the last element, inclusive of both. This just speeds up the code a bit (I suppose, check out my modified code). Regarding the ampersand operator, yup, the rest of the expression is just discarded if the previous one is false. This is what's called as 'short-circuiting'. It makes the code a bit faster
4th Jan 2022, 10:55 AM
Œ ㅤ
Œ ㅤ - avatar