Movatterモバイル変換


[0]ホーム

URL:


Open In App

Given a strings, determine the number of substrings that satisfy certain criteria. For example we are given a string s="hellohellohello" we need to count how many time the substring occur in the given string suppose we need to find the substring "hello" so that the count becomes 3. We can use methods like count().

Usingstr.count()

count() method returns the number of non-overlapping occurrences of a substring in the string.

Python
# Define the input string and the substring to counts="hellohellohello"sub="hello"# Use the count() method to find the number of occurrences of the substringc=s.count(sub)print(c)

Output
3

Explanation:

  • count() method counts the number of non-overlapping occurrences of the substring"hello" within the strings.
  • In this case, it returns3 because the substring"hello" appears three times in"hellohellohello".

Using a For Loop with String Slicing

Afor loop can iterate through the string, using slicing to check for the occurrence of a substring. For example, usings[i:i+len(substring)] inside the loop allows for comparing each slice of the string to the target substring

Python
s1="hellohellohello"sub="hello"# Initialize count to zerocnt=0# Iterate through the string to check for the substringforiinrange(len(s)-len(sub)+1):ifs[i:i+len(sub)]==sub:# If substring matches, increment countcnt+=1print(cnt)

Output
3

Explanation:

  • for loop iterates through the strings, using slicing (s[i:i+len(substring)]) to extract substrings of the same length assubstring and compare them.
  • If the sliced substring matches the targetsubstring, thecount is incremented, resulting in a count of3 for the occurrences of"hello" in"hellohellohello".

Using List Comprehension

Generate a list of indices where the substring starts and count its length.

Python
# Input string and substring to counts="hello world, hello universe"sub="hello"# Count occurrences of the substring using a generator expressionc=sum(1foriinrange(len(s)-len(sub)+1)ifs[i:i+len(sub)]==sub)print(c)

Output
2

Explanation:

  • Generator expression iterates through all possible starting indices ins and counts matches ofsub with slices ofs.
  • Range ensures slicing stays within bounds to compare each substring correctly.

Improve

Explore

Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp