[BAEL-2141] - How to check if a string contains all the letters of the alphabet?

This commit is contained in:
kartiksingla 2018-08-23 21:44:01 +05:30
parent b8592c463c
commit b8ae8ace4a
2 changed files with 55 additions and 0 deletions

View File

@ -0,0 +1,35 @@
package com.baeldung.algorithms.string;
public class EnglishAlphabetLetters {
public static boolean checkStringForAllTheLetters(String input) {
boolean[] visited = new boolean[26];
int index = 0;
for (int id = 0; id < input.length(); id++) {
if ('a' <= input.charAt(id) && input.charAt(id) <= 'z') {
index = input.charAt(id) - 'a';
} else if ('A' <= input.charAt(id) && input.charAt(id) <= 'Z') {
index = input.charAt(id) - 'A';
}
visited[index] = true;
}
for (int id = 0; id < 26; id++) {
if (!visited[id]) {
return false;
}
}
return true;
}
public static boolean checkStringForAllLetterUsingStream(String input) {
long c = input.toLowerCase().chars().filter(ch -> ch >= 'a' && ch <= 'z').distinct().count();
return c == 26;
}
public static void main(String[] args) {
checkStringForAllLetterUsingStream("intit");
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.algorithms.string;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class EnglishAlphabetLettersTest {
@Test
void givenString_whenContainsAllCharacter_thenTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllTheLetters(input));
}
@Test
void givenString_whenContainsAllCharacter_thenUsingStreamExpectTrue() {
String input = "Farmer jack realized that big yellow quilts were expensive";
Assertions.assertTrue(EnglishAlphabetLetters.checkStringForAllLetterUsingStream(input));
}
}