In: Computer Science
Exercise 3 – Strings
Using a function Write a program that prompts the user to enter two inputs: some text and a word. The program outputs the starting indices of all occurrences of the word in the text. If the word is not found, the program should output “not found”.
Example1:
Input1: my dog and myself are going to my friend
Input2: my
Output: 0 11 31
Example 2:
Input1: Programming is fun
Input 2: my
Output: not found
import java.util.Scanner; public class SubStringsIndexes { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String s1, s2; int ind, sum = 0; System.out.print("Input 1: "); s1 = scanner.nextLine(); System.out.print("Input 2: "); s2 = scanner.nextLine(); if(s1.contains(s2)) { while (s1.contains(s2)) { ind = s1.indexOf(s2); System.out.print((sum+ind) + " "); sum += s2.length()+ind; s1 = s1.substring(ind + s2.length()); } System.out.println(); } else{ System.out.println("not found"); } } }