Write a program which takes a string and a word from the userand search that word in the string and count how many timesthat word comes in the string.

Respuesta :

Answer:

Following is the Java Code:-

import java.io.*; // package of java input output

import java.util.*; // package for using scanner class  

class Main{  

static int count(String str, String word) // create as function

{  

String a1[] = str.split(" "); // splitting the string by space

int c = 0; // initialization of count variable

for (int k = 0; k< a1.length; k++)  

{  

if (word.equals(a1[k])) // match the string to word if condition is matched

c++; // increment of count

}  

return c++;  

}  

public static void main(String args[]) // main method

{  

Scanner ob1 = new Scanner(System.in); // Creating a Scanner object

System.out.println("Enter the string:");

String str1,word1;  

str1= ob1.nextLine();

System.out.println("Enter word you want to search without spaces:");

word1 = ob1.nextLine();

System.out.println(count(str1, word1)); // calling and printing ther word

}  

}

Output:-

Enter the string:

deep das dev das

Enter the word you want to search without spaces :

das

2

Explanation:

I have taken an array of strings to store the words in the string entered and checking the word entered is equal to any word in the string if it is then updating the count.After that returning the count .