I am doing a homework assignment for my Computer Science course. The task is to get a users input, remove all of the vowels, and then print the new statement.
I know I could easily do it with this code:
string.replaceAll("[aeiou](?!\\b)", "")
But my instructor wants me to use nested if and else if statements to achieve the result. Right now I am using something like this:
if(Character.isLetter('a')){
'do something'
}else if(Character.isLetter('e')){
'do something else'
But I am not sure what to do inside the if and else if statements. Should I delete the letter? Or is there a better way to do this?
Seeing as this is my homework I don't want full answers just tips. Thanks!
I think what he might want is for you to read the string, create a new empty string (call it s), loop over your input and add all the characters that are not vowels to s (this requires an if statement). Then, you would simply print the contents of s.
Edit: You might want to consider using a StringBuilder for this because repetitive string concatenation can hinder performance, but the idea is the same. But to be honest, I doubt it would make a noticeable difference for this type of thing.
Character.isLetter('a')
Character.isLetter(char) tells you if the value you give it is a letter, which isn't helpful in this case (you already know that "a" is a letter).
You probably want to use the equality operator, ==, to see if your character is an "a", like:
char c = ...
if(c == 'a') {
...
} else if (c == 'e') {
...
}
You can get all of the characters in a String in multiple ways:
As an array with String.toCharArray()
Getting each character from the String using String.charAt(index)
I think you can iterate through the character check if that is vowel or not as below:
define a new string
for(each character in input string)
//("aeiou".indexOf(character) <0) id one way to check if character is consonant
if "aeiou" doesn't contain the character
append the character in the new string
If you want to do it in O(n) time
Iterate over the character array of your String
If you hit a vowel skip the index and copy over the next non vowel character to the vowel position.
You will need two counters, one which iterates over the full string, the other which keeps track of the last vowel position.
After you reach the end of the array, look at the vowel tracker counter - is it sitting on a vowel, if not then the new String can be build from index 0 to 'vowelCounter-1'.
If you do this is in Java you will need extra space to build the new String etc. If you do it in C you can simply terminate the String with a null character and complete the program without any extra space.
I don't think your instructor wanted you to call Character.isLetter('a') because it's always true.
The simplest way of building the result without regexp is using a StringBuilder and a switch statement, like this:
String s = "quick brown fox jumps over the lazy dog";
StringBuffer res = new StringBuffer();
for (char c : s.toCharArray()) {
switch(c) {
case 'a': // Fall through
case 'u': // Fall through
case 'o': // Fall through
case 'i': // Fall through
case 'e': break; // Do nothing
default: // Do something
}
}
s = res.toString();
System.out.println(s);
You can also replace this with an equivalent if, like this:
if (c!='a' && c!='u' && c!='o' && c!='i' && c!='e') {
// Do something
}
Related
I was wondering how I should write this if statement in my assignment.
The question is:
Print option 2 if one of the strings begins with the letter w or has 5 characters.
I would use the .contains to find the "w".
if (two.contains("w") {
System.out.println(two);
but the one with the characters I am unsure how to find the method.
If you have a List or Set, you may need to loop over them one by one, to do the actual comparing try this:
(two.startsWith("w") || two.length() == 5) {
System.out.println(two);
}
The first condition checks if given String object starts with given char, and the other one counts the number of characters in the String and checks your desired lenght, which is 5.
For more useful information and String object has, check this out String (Java Platform SE 7)
String aString = ".....";
if (aString.startsWith("w") || aString.length() == 5) {
System.out.println("option 2");
}
The method .contains returns true if find a substring (in this case "w") in string. You should use .startsWith method.
I am developing a program that asks the user for a word / letter. In this example i will type 'a'. The program will then see if 'a' is a prefix,suffix or infix of the word. I quickly figured out how to figure out the prefix and suffix using "startsWith(String s).
However, I wonder how I will be able to see the infix of the String s. The infix in hat is 'a' but how can I make my program figure that out?
So my question is:
How will my program be able to tell if 'a' is an infix of "hat"?
Is there some sort of algorithm or method I should use? I am really stuck here.
I don't have any code due to the fact that I don't know how to face this problem.
Thanks in advance!
Use indexOf(String str):
String word = "hat";
String letter = "a";
int index = word.indexOf(letter);
if (index == -1) {
System.out.println("Not found");
} else if (index == 0) {
System.out.println("Prefix");
} else if (index == word.length() - letter.length()) {
System.out.println("Suffix");
} else {
System.out.println("Infix");
}
According to many sites on definition of Infix, it is an affix inserted inside a word stem.
I can tell to have dictionary of whole english words( it'll be having only formal words, and infix words are informal ), and compare with given word.
For comparison, use the longest letter match with score and take the highest score (some tuning might be required ) because it will be comparing against huge set of words.
But if you just ask a word on middle, just check if its neither prefix nor suffix. This won't work for all cases.
https://www.thoughtco.com/infix-words-and-grammar-1691167
I've got some String, and I'd like to replace some chars in it. Everything was running fine until the String hasn't two or more same chars, the program just replacing the first one, and I'm not able to change the second one.
StringBuilder userTitleBuilder = new StringBuilder(conversedTitle);
while (score>1) {
userLetter = userInput.next().charAt(0);
if (movieTitle.contains(String.valueOf(userLetter))) {
charIndex = movieTitle.indexOf(userLetter);
userTitleBuilder.replace(charIndex,userTitleBuilder.length(), String.valueOf(userLetter));
System.out.println(userTitleBuilder);
} else {
--score;
System.out.println("Wrong\nTries left "+score);
}
}
Here's the explanation of this code:
User from the start the program has a score equals to 10. userLetter it's just a char that will get some letter from the user, then if statement checking if movieTitle variable has char equals to that user just entered, if yes, charIndex will have it position (but it contains only first index, what if in word are more same letters?) now userTitleBuilder replace the chars in string that has that many "_" that movieTitle lenght, it's just covering the title.
*movieTitle and userTitleBuilder has the same value = "CocaCola"
I'd like to not get ready solution. I'd like to have some kind of hint, how do I replace more than one same character in String
A method called String.replace("old","new") can be used.
Follow this doc.
I have a scanner that reads a 7 character alphanumeric code (inputted by the user). the String variable is called "code".
The last character of the code (7th character, 6th index) MUST BE NUMERIC, while the rest may be either numeric or alphabetical.
So, I sought ought to make a catch, which would stop the rest of the method from executing if the last character in the code was anything but a number (from 0 - 9).
However, my code does not work as expected, seeing as even if my code ends in an integer between 0 and 9, the if statement will be met, and print out "last character in code is non-numerical).
example code: 45m4av7
CharacterAtEnd prints out as the string character 7, as it should.
however my program still tells me my code ends non-numerically.
I'm aware that my number values are string characters, but it shouldnt matter, should it?
also I apparently cannot compare actual integer values with an "|", which is mainly why im using String.valueOf, and taking the string characters of 0-9.
String characterAtEnd = String.valueOf(code.charAt(code.length()-1));
System.out.println(characterAtEnd);
if(!characterAtEnd.equals(String.valueOf(0|1|2|3|4|5|6|7|8|9))){
System.out.println("INVALID CRC CODE: last character in code in non-numerical.");
System.exit(0);
I cannot for the life of me, figure out why my program is telling me my code (that has a 7 at the end) ends non-numerically. It should skip the if statement and continue on. right?
The String contains method will work here:
String digits = "0123456789";
digits.contains(characterAtEnd); // true if ends with digit, false otherwise
String.valueOf(0|1|2|3|4|5|6|7|8|9) is actually "15", which of course can never be equal to the last character. This should make sense, because 0|1|2|3|4|5|6|7|8|9 evaluates to 15 using integer math, which then gets converted to a String.
Alternatively, try this:
String code = "45m4av7";
char characterAtEnd = code.charAt(code.length() - 1);
System.out.println(characterAtEnd);
if(characterAtEnd < '0' || characterAtEnd > '9'){
System.out.println("INVALID CRC CODE: last character in code in non-numerical.");
System.exit(0);
}
You are doing bitwise operations here: if(!characterAtEnd.equals(String.valueOf(0|1|2|3|4|5|6|7|8|9)))
Check out the difference between | and ||
This bit of code should accomplish your task using regular expressions:
String code = "45m4av7";
if (!code.matches("^.+?\\d$")){
System.out.println("INVALID CRC CODE");
}
Also, for reference, this method sometimes comes in handy in similar situations:
/* returns true if someString actually ends with the specified suffix */
someString.endsWith(suffix);
As .endswith(suffix) does not take regular expressions, if you wanted to go through all possible lower-case alphabet values, you'd need to do something like this:
/* ASCII approach */
String s = "hello";
boolean endsInLetter = false;
for (int i = 97; i <= 122; i++) {
if (s.endsWith(String.valueOf(Character.toChars(i)))) {
endsInLetter = true;
}
}
System.out.println(endsInLetter);
/* String approach */
String alphabet = "abcdefghijklmnopqrstuvwxyz";
boolean endsInLetter2 = false;
for (int i = 0; i < alphabet.length(); i++) {
if (s.endsWith(String.valueOf(alphabet.charAt(i)))) {
endsInLetter2 = true;
}
}
System.out.println(endsInLetter2);
Note that neither of the aforementioned approaches are a good idea - they are clunky and rather inefficient.
Going off of the ASCII approach, you could even do something like this:
ASCII reference : http://www.asciitable.com/
int i = (int)code.charAt(code.length() - 1);
/* Corresponding ASCII values to digits */
if(i <= 57 && i >= 48){
System.out.println("Last char is a digit!");
}
If you want a one-liner, stick to regular expressions, for example:
System.out.println((!code.matches("^.+?\\d$")? "Invalid CRC Code" : "Valid CRC Code"));
I hope this helps!
I would like to find an efficient way (not scanning the String 10,000 times, or creating lots of intermediary Strings for holding temporary results, or string bashing, etc.) to write a method that accepts a String and determine if it meets the following criteria:
It is at least 2 characters in length
The first character is uppercased
The remaining substring after the first character contains at least 1 lowercased character
Here's my attempt so far:
private boolean isInProperForm(final String token) {
if(token.length() < 2)
return false;
char firstChar = token.charAt(0);
String restOfToken = token.substring(1);
String firstCharAsString = firstChar + "";
String firstCharStrToUpper = firstCharAsString.toUpperCase();
// TODO: Giving up because this already seems way too complicated/inefficient.
// Ignore the '&& true' clause - left it there as a placeholder so it wouldn't give a compile error.
if(firstCharStrToUpper.equals(firstCharAsString) && true)
return true;
// Presume false if we get here.
return false;
}
But as you can see I already have 1 char and 3 temp strings, and something just doesn't feel right. There's got to be a better way to write this. It's important because this method is going to get called thousands and thousands of times (for each tokenized word in a text document). So it really really needs to be efficient.
Thanks in advance!
This function should cover it. Each char is examined only once and no objects are created.
public static boolean validate(String token) {
if (token == null || token.length() < 2) return false;
if (!Character.isUpperCase(token.charAt(0)) return false;
for (int i = 1; i < token.length(); i++)
if (Character.isLowerCase(token.charAt(i)) return true;
return false;
The first criteria is simply the length - this data is cached in the string object and is not requiring traversing the string.
You can use Character.isUpperCase() to determine if the first char is upper case. No need as well to traverse the string.
The last criteria requires a single traversal on the string- and stop when you first find a lower case character.
P.S. An alternative for the 2+3 criteria combined is to use a regex (not more efficient - but more elegant):
return token.matches("[A-Z].*[a-z].*");
The regex is checking if the string starts with an upper case letter, and then followed by any sequence which contains at least one lower case character.
It is at least 2 characters in length
The first character is
uppercased
The remaining substring after the first character contains
at least 1 lowercased character
Code:
private boolean isInProperForm(final String token) {
if(token.length() < 2) return false;
if(!Character.isUpperCase(token.charAt(0)) return false;
for(int i = 1; i < token.length(); i++) {
if(Character.isLowerCase(token.charAt(i)) {
return true; // our last criteria, so we are free
// to return on a met condition
}
}
return false; // didn't meet the last criteria, so we return false
}
If you added more criteria, you'd have to revise the last condition.
What about:
return token.matches("[A-Z].*[a-z].*");
This regular expression starts with an uppercase letter and has at least one following lowercase letter and therefore meets your requirements.
To find if the first character is uppercase:
Character.isUpperCase(token.charAt(0))
To check if there is at least one lowercase:
if(Pattern.compile("[a-z]").matcher(token).find()) {
//At least one lowercase
}
To check if first char is uppercase you can use:
Character.isUpperCase(s.charAt(0))
return token.matches("[A-Z].[a-z].");