🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
Counting the number of times a specific substring appears in a larger string is a common text-processing task. While Python provides built-in methods for this, knowing how to do it from scratch can enhance one's understanding of string manipulation.
In this blog post, we will learn how to write a Python program to count occurrences of a substring in a string.
2. Program Overview
1. Create a function that iterates through the main string and checks for occurrences of the substring.
2. Accept the main string and the target substring from the user.
3. Call the function to count the occurrences.
4. Display the result to the user.
3. Code Program
# Python program to count occurrences of a substring in a string
def count_substring(main_str, sub_str):
"""Function to count occurrences of a substring."""
count = 0 # Initialize the count
index = 0 # Start from the beginning of the string
while index < len(main_str):
position = main_str.find(sub_str, index)
if position == -1:
return count # No more occurrences found
count += 1
index = position + 1 # Move past the last found substring
return count
# Accept input from the user
string_input = input("Enter the main string: ")
substring_input = input("Enter the substring to search for: ")
# Calculate the occurrences
occurrences = count_substring(string_input, substring_input)
# Display the result
print(f"The substring '{substring_input}' appears {occurrences} times in the string '{string_input}'.")
Output:
Enter the main string: java guides java examples Enter the substring to search for: java The substring 'java' appears 2 times in the string 'java guides java examples'.
4. Step By Step Explanation
1. The function count_substring is defined to count the occurrences of the sub_str inside main_str.
2. A while loop runs until the end of the main string. Within the loop, we use the find method of the string which returns the starting position of the first occurrence of the substring. If no more occurrences are found, it returns -1.
3. Every time the substring is found, we increment our count.
4. To avoid counting the same occurrence multiple times, we set index to the position after the last found occurrence. This way, the search continues from the next character onwards.
5. Outside the function, we get the main string and target substring from the user.
6. The function is then called with these values, and the result is displayed.
7. The provided output section showcases the output for a sample input where the main string is "hello hello world" and the substring is "hello".
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment