Question 02 of 04

Find All Substring Index Occurrences

Write a Python program that accepts two strings (main string and substring) and returns the indices of all occurrences of the second string in the first string as a list. If the second string is not present in the first string, it should return -1.

C++
def find_all_occurrences(main_str, sub_str):
    """
    Returns a list of all starting indices of sub_str in main_str.
    Returns -1 if sub_str is not found.
    """
    if not sub_str:
        return -1
        
    indices = []
    start_pos = 0
    
    while True:
        pos = main_str.find(sub_str, start_pos)
        if pos == -1:
            break
        indices.append(pos)
        start_pos = pos + 1  # Move forward to search for overlapping/subsequent occurrences
        
    return indices if len(indices) > 0 else -1

def main():
    str1 = input("Enter the first (main) string: ")
    str2 = input("Enter the second (target substring): ")
    
    result = find_all_occurrences(str1, str2)
    
    print(f"\nMain String:      "{str1}"")
    print(f"Target Substring: "{str2}"")
    print(f"Resulting Indices: {result}")

if __name__ == "__main__":
    main()
Question 2 of 4