Occurence Of A Word In A String Using Java

 package demo;


import java.util.stream.Stream;


public class OccurenceString {

public static void main(String[] args) {


String str = "helloworld this is uj enjoying day with uj";

System.out.println(countOccurences(str, "uj"));

System.out.println(countOccurencesIn8(str, "uj"));

}


// java8

private static int countOccurencesIn8(String str, String word) {

return (int)Stream.of(str.split(" ")).filter(x -> x.equals(word)).count();


}


private static int countOccurences(String str, String word) {

String a[] = str.split(" ");

int count = 0;

for (int i = 0; i < a.length; i++) {

if (word.equals(a[i])) {

count++;

}

}

return count;

}

}


Comments

Popular posts from this blog

3 Lines of Code And You Can Download Your Favourite Youtube Video.

Leetcode Problem(Easy) Roman to Integer

Leetcode : (Find Minimum in Rotated Sorted Array)