Use this to compares a String
to another ignoring case considerations.
There are many ways to solve your problem. I have listed a few of them and I suggest you to try some more ways once you have understood these ones.
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String str = in.nextLine();
System.out.print("Enter the word: ");
String word = in.nextLine();
long count = 0;
// Using Stream API
count = Arrays.stream(str.split("\\s+|\\p{Punct}")).filter(w -> w.equalsIgnoreCase(word)).count();
System.out.println(count);
// Pre-Java8 way
count = 0;
for (String w : str.split("\\s+|\\p{Punct}")) {
if (w.equalsIgnoreCase(word)) {
count++;
}
}
System.out.println(count);
// Using regex
count = 0;
Matcher matcher = Pattern.compile("(?i)\\b" + word + "\\b").matcher(str);
while (matcher.find()) {
count++;
}
System.out.println(count);
}
}
A sample run:
Enter the sentence: deadline is Deadline, so try not to extend DeaDLINE!!!
Enter the word: deadline
3
3
3
- The regex,
\s+|\p{Punct}
means one or more whitespace characters or a punctuation character
(?i)
in the beginning of a regex pattern makes it case-insensitive.
\b
specifies a word boundary.
If you are looking to match anagrams, you can define a function to find if the two words are anagram and the rest of the processing will be same as above.
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the sentence: ");
String str = in.nextLine();
System.out.print("Enter the word: ");
String word = in.nextLine();
long count = 0;
// Using Stream API
count = Arrays.stream(str.split("\\s+|\\p{Punct}")).filter(w -> anagrams(w, word)).count();
System.out.println(count);
// Pre-Java8 way
count = 0;
for (String w : str.split("\\s+|\\p{Punct}")) {
if (anagrams(w, word)) {
count++;
}
}
System.out.println(count);
}
static boolean anagrams(String str1, String str2) {
if (str1.length() == str1.length()) {
// Get the char[] from strings after converting them to the same case
char[] arr1 = str1.toLowerCase().toCharArray();
char[] arr2 = str2.toLowerCase().toCharArray();
Arrays.sort(arr1);
Arrays.sort(arr2);
return (Arrays.equals(arr1, arr2));
}
return false;
}
}
Output:
Enter the sentence: deadline is Deadline, so try not to extend DeaDLINE!!!
Enter the word: liNedeAd
3
3
Important links:
- Lesson: Regular Expressions
- Reference - What does this regex mean?
- Processing Data with Java SE 8 Streams, Part 1