Check a string for consonants - java

I want to write a method to check a string for consonants using either .contains or .indexOf.
I guess I could do it the long way and check for every consonant in the alphabet but I know there is a better way. This is what I have so far but like I said this is sort of the long way, I think.
public boolean containsConsonant(String searchString) {
if(searchString.contains("b") || searchString.contains("c")){
return true;
}

I think a simple for loop is most readable here, you can test that a character is within the desired range with a boolean and. And you can use an or test to skip vowels. Something like,
public boolean containsConsonant(String searchString) {
if (searchString == null) {
return false;
}
for (char ch : searchString.toCharArray()) {
char lower = Character.toLowerCase(ch);
if (lower >= 'a' && lower <= 'z') {
if (lower == 'a' || lower == 'e' || lower == 'i' ||
lower == 'o' || lower == 'u') continue;
return true;
}
}
return false;
}
Optimization
You could then optimize the above (and directly to your question) by using contains on an extracted constant String of vowels. Something like,
private static final String vowels = "aeiou";
public static boolean containsConsonant(final String searchString) {
if (searchString == null) {
return false;
}
for (char ch : searchString.toCharArray()) {
char lower = Character.toLowerCase(ch);
if (lower >= 'a' && lower <= 'z' && !vowels.contains(String.valueOf(lower))) {
return true;
}
}
return false;
}

I see that you explicitly ask using contains or indexOf
in case - if you can use matches - it would be very easy to implement.
public boolean containsConsonant(String searchString){
String consonants = ".*[bcdfghj].*"; //list the characters to be checked
return searchString.matches(consonants);
}

you can create say an array containing all consonants and then run it using a loop
e.g.
String[] consonants{"b", "c",....}
boolean containsConsonants(String searchString, String[]arr){
for (String consonant: arr){
if(searchString.contains(str)){ return true} return False

Related

How do I handle punctuation in this Pig Latin translator?

The rest of the code is working perfectly but I cannot figure out how to prevent punctuation from being translated.
public class PigLatintranslator
{
public static String translateWord (String word)
{
String lowerCaseWord = word.toLowerCase ();
int pos = -1;
char ch;
for (int i = 0 ; i < lowerCaseWord.length () ; i++)
{
ch = lowerCaseWord.charAt (i);
if (isVowel (ch))
{
pos = i;
break;
}
}
if (pos == 0 && lowerCaseWord.length () != 1) //translates if word starts with vowel
{
return lowerCaseWord + "way"; // Adding "way" to the end of string
}
else if (lowerCaseWord.length () == 1) //Ignores words that are only 1 character
{
return lowerCaseWord;
}
else if (lowerCaseWord.charAt(0) == 'q' && lowerCaseWord.charAt(1) == 'u')//words that start with qu
{
String a = lowerCaseWord.substring (2);
return a + "qu" + "ay";
}
else
{
String a = lowerCaseWord.substring (1);
String b = lowerCaseWord.substring (0,1);
return a + b + "ay"; // Adding "ay" at the end of the extracted words after joining them.
}
}
public static boolean isVowel (char ch) checks for vowel
{
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'y')
{
return true;
}
return false;
}
}
I need the translation to ignore punctuation. For example "Question?" should be translated to "estionquay?" (question mark still in the same position and not translated)
As Andreas said, if the function is expecting only one word, it should be the responsibility of the calling function to ensure there's no full sentence or punctuation being passed to it. With that said, if you require the translator to handle this, you need to find the index of the string where the punctuation or non-letter character occurs. I added in a main method to test the function:
public static void main(String[] args) {
System.out.println(translateWord("QUESTION?"));
}
I added a loop into the qu case to find the punctuation being input, the two checks are to see if the character at position i is inside the range of a - z. The sub-string then only goes to the point where the punctuation is found.
int i;
for (i = 0; i < lowerCaseWord.length(); i++) {
if(lowerCaseWord.charAt(i) > 'z' || lowerCaseWord.charAt(i) < 'a') {
break;
}
}
String a = lowerCaseWord.substring (2, i);
String b = lowerCaseWord.substring(i);
return a + "qu" + "ay" + b;
This may need some tweaking if you're worried about words with hyphens and whatnot but this should put across the basic idea.
Here's the output I received:
$javac PigLatintranslator.java
$java -Xmx128M -Xms16M PigLatintranslator
estionquay?

Java check if parameter contains vowels

I am kind of new to Java coming from a JavaScript background. I am trying to check if a given parameter contains vowels and if so, return true. This is what I have so far:
public class StringUtils {
public static boolean isVowel(String s) {
String x = s.toLowerCase();
if(x.indexOf('a' || 'e' || 'i' || 'o' || 'u')) {
return true;
} else {
return false;
}
}
}
How should this be done in Java?
You can try this method to check for vowels:
public static boolean isVowel(char c) {
return "AEIOUaeiou".indexOf(c) != -1;
}
You can try regex also:
yourString.matches("[AEIOUaeiou]")
smth like that

isVowel() method with a character in a String

I have a text file with a bunch of words. One part of my program is supposed to, based on the user input, scan this list and insert into the output file the words that contain the requested number of vowels. I have a isVowel method that returns a boolean, but it doesn't seem to work--the output is just an empty list.
Here's the method:
public boolean isVowel(char c)
{
if(c=='a' || c=='A' || c=='e' || c=='E' || c=='i' || c=='I' || c=='o' || c=='O' || c=='u' || c=='U')
{
return true;
}
else
{
return false;
}
}
}
Here's the part of the program where it is used:
public ArrayList<String> vowelHeavy(int n, int m)
{
int vowels = 0;
while(input.hasNextLine())
{
word = input.nextLine();
if (word.length() == n)
{
for(int i = 0; i < word.length(); i++)
{
if(isVowel(word.charAt(i)) == true)
{
vowels++;
}
}
if (vowels == m)
{
output.add(word);
}
}
word = input.nextLine();
}
return output;
}
Your biggest problem is you are not resetting you vowels counting variable when you test a new word. The value just keeps accumulating the total vowels in the file.
Change:
int vowels = 0;
while(input.hasNextLine()) {
...
to:
while(input.hasNextLine()) {
int vowels = 0;
...
As an aside, most of your code, including the isVowel() method, could be eliminated with a single line:
int vowels = word.replaceAll("[^aeiouAEIOU]", "").length();
This works by eliminating from the word all characters that aren't vowels; what's left are the vowels, so just take the length to get the count.
Theres a much easier way to write this code:
public boolean isVowel(char c){
return(your boolean tests);
}
2 things:
If the word.length() == n test is never true, then output is never changed. Please make sure that test is correct.
This statement exists at the top AND bottom of the while loop, causing you to ignore every other input line:
word = input.nextLine();

Writing a method to remove vowels in a Java String [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am a beginner of programming, and am writing a Java method to remove vowel in Strings, but I do not know how to fix this error: ";" expected :
public String disemvowel(String s) {
boolean isVowel(char c);
if (c == 'a') {
return true;
} else if if (c == 'e') {
return true;
} else if if (c == 'i') {
return true;
} else if if (c == 'o') {
return true;
} else if if (c == 'u') {
return true;
}
String notVowel = "";
int l = s.length();
for (int z = 0; z <= l; z++) {
if (isVowel == "false") {
char x = s.charAt(z);
notVowel = notVowel + x;
}
}
return notVowel;
}
String str= "Your String";
str= str.replaceAll("[AEIOUaeiou]", "");
System.out.println(str);
A much simpler approach would be to do the following:
String string = "A really COOL string";
string = string.replaceAll("[AaEeIiOoUu]", "");
System.out.println(string);
This will apply the regular expression, [AaEeIiOoUu] to string. This expression will match all vowels in the character group [AaEeIiOoUu] and replace them with "" empty string.
You've got a lot of syntax errors.
boolean isVowel(char c); - not sure what you're doing with this. if you want it as a separate method, separate it out (and don't place a semicolon after it, which would be invalid syntax.
else if if is invalid syntax. If you're doing an else if, then you only need the one if.
Even if the code would compile, for (int z = 0; z <= l; z++) will cause you to step off of the String. Remove the <= in favor of <.
isVowel == "false" is never going to work. You're comparing a String to a boolean. You want !isVowel instead.
Putting the syntax errors aside, think of it like this.
You have a string that contains vowels. You wish to have a string that doesn't contain vowels.
The most straightforward approach is to iterate over the String, placing all non-vowel characters into a separate String, which you then return.
Interestingly enough, the half-method you have there can accomplish the logic of determining whether something is or isn't a vowel. Extract that to its own method. Then, call it in your other method. Do take into account capital letters though.
I leave the rest as an exercise to the reader.
Here is your code, without changing any logic, but unscrambling the isVowel method:
public String disemvowel(String s) {
// Removed the "isVowel" method from here and moved it below
String notVowel = "";
int l = s.length();
for (int z = 0; z <= l; z++) {
// Note that the "isVowel" method has not been called.
// And note that, when called, isVowel returns a boolean, not a String.
// (And note that, as a general rule, you should not compare strings with "==".)
// So this area needs a lot of work, but we'll start with this
boolean itIsAVowel = isVowel(s.charAt(z));
// (I made the variable name "itIsAVowel" to emphasize that it's name has nothing to do with the method name.
// You can make it "isVowel" -- the same as the method -- but that does not in any way change the function.)
// Now take it from there...
if (isVowel == "false") {
char x = s.charAt(z);
notVowel = notVowel + x;
}
}
return notVowel;
}
// You had this line ending with ";"
boolean isVowel(char c) {
if (c == 'a') {
return true;
// Note that you coded "if if" on the lines below -- there should be only one "if" per line, not two
} else if if (c == 'e') {
return true;
} else if if (c == 'i') {
return true;
} else if if (c == 'o') {
return true;
} else if if (c == 'u') {
return true;
}
// You were missing this final return
return false;
}
(Yes, I know this should be a comment, but you can't put formatted code in a comment.)
You could try something like this:
public static String removeVowels(final String string){
final String vowels = "AaEeIiOoUu";
final StringBuilder builder = new StringBuilder();
for(final char c : string.toCharArray())
if(vowels.indexOf(c) < 0)
builder.append(c);
return builder.toString();
}

How to determine a string is english or arabic?

Is there a way to determine a string is English or Arabic?
Here is a simple logic that I just tried:
public static boolean isProbablyArabic(String s) {
for (int i = 0; i < s.length();) {
int c = s.codePointAt(i);
if (c >= 0x0600 && c <= 0x06E0)
return true;
i += Character.charCount(c);
}
return false;
}
It declares the text as arabic if and only if an arabic unicode code point is found in the text. You can enhance this logic to be more suitable for your needs.
The range 0600 - 06E0 is the code point range of Arabic characters and symbols (See Unicode tables)
Java in itself supports various language checks by unicode, Arabic is also supported. Much simpler and smallest way to do the same is by UnicodeBlock
public static boolean textContainsArabic(String text) {
for (char charac : text.toCharArray()) {
if (Character.UnicodeBlock.of(charac) == Character.UnicodeBlock.ARABIC) {
return true;
}
}
return false;
}
A minor change to cover all arabic characters and symbols range
private boolean isArabic(String text){
String textWithoutSpace = text.trim().replaceAll(" ",""); //to ignore whitepace
for (int i = 0; i < textWithoutSpace.length();) {
int c = textWithoutSpace.codePointAt(i);
//range of arabic chars/symbols is from 0x0600 to 0x06ff
//the arabic letter 'لا' is special case having the range from 0xFE70 to 0xFEFF
if (c >= 0x0600 && c <=0x06FF || (c >= 0xFE70 && c<=0xFEFF))
i += Character.charCount(c);
else
return false;
}
return true;
}
You can usually tell by the code points within the string itself. Arabic occupies certain blocks in the Unicode code space.
It's a fairly safe bet that, if a substantial proportion of the characters exist in those blocks (such as بلدي الحوامات مليء الثعابينة), it's Arabic text.
This answer is somewhat correct. But when we combine Farsi and English letters it returns TRUE!, which is not true.
Here I modified the same method so that it works well
public static boolean isProbablyArabic(String s) {
for (int i = 0; i < s.length();) {
int c = s.codePointAt(i);
if (!(c >= 0x0600 && c <= 0x06E0))
return false;
i += Character.charCount(c);
}
return true;
}
You could use N-gram-based text categorization (google for that phrase) but it is not a fail-proof technique, and it may require a not too short string.
You might also decide that a string with only ASCII letters is not Arabic.
English characters tend to be in these 4 Unicode blocks:
BASIC_LATIN
LATIN_1_SUPPLEMENT
LATIN_EXTENDED_A
GENERAL_PUNCTUATION
public static boolean isEnglish(String text) {
boolean onlyEnglish = false;
for (char character : text.toCharArray()) {
if (Character.UnicodeBlock.of(character) == Character.UnicodeBlock.BASIC_LATIN
|| Character.UnicodeBlock.of(character) == Character.UnicodeBlock.LATIN_1_SUPPLEMENT
|| Character.UnicodeBlock.of(character) == Character.UnicodeBlock.LATIN_EXTENDED_A
|| Character.UnicodeBlock.of(character) == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
onlyEnglish = true;
} else {
onlyEnglish = false;
}
}
return onlyEnglish;
}
Just an adaptation of existing answer to Kotlin:
fun String.textContainsArabic(): Boolean =
any { Character.UnicodeBlock.of(it) == Character.UnicodeBlock.ARABIC }
I tried this with my code and it works fine.
Using codePointAt which is a method that returns the Unicode value of the character at the specified index in a string.
public static boolean isItArabic(String someText)
{
for(int i = 0; i<someText.length(); i++)
{
int point = someText.codePointAt(i);
if(!(point >= 1536 && point <= 1791)) {
return false;
}
}
return true;
}
Try This :
internal static bool ContainsArabicLetters(string text)
{
foreach (char character in text.ToCharArray())
{
if (character >= 0x600 && character <= 0x6ff)
return true;
if (character >= 0x750 && character <= 0x77f)
return true;
if (character >= 0xfb50 && character <= 0xfc3f)
return true;
if (character >= 0xfe70 && character <= 0xfefc)
return true;
}
return false;
}

Categories

Resources