- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to count number of substring present in string
Suppose we have a string s and a substring t. We have to count how many times t occurs in s.
So, if the input is like s = "abaabcaabababaab", t = "aab", then the output will be 3 because the substrings are ab(aab)c(aab)abab(aab).
To solve this, we will follow these steps −
- cnt := 0
- for i in range 0 to (size of s - size of t), do
- if substring of s[from index i to i + size of t - 1] is same as t, then
- cnt := cnt + 1
- if substring of s[from index i to i + size of t - 1] is same as t, then
- return cnt
Example
Let us see the following implementation to get better understanding
def solve(s, t): cnt = 0 for i in range(0, len(s) - len(t) + 1): if s[i:i + len(t)] == t: cnt = cnt + 1 return cnt s = "abaabcaabababaab" t = "aab" print(solve(s, t))
Input
"abaabcaabababaab", "aab"
Output
3
Advertisements