Attempting to remove characters from a string - java

I am attempting to remove vowels from a randomly generated 20 letter word. I have to use substring for this assignment but am having issues with it conceptually. With this code, the value of word never changes and stays its original value. When I do i+2 for the second half of the string it jumps two characters and messes up when there are two vowels directly after one another. If I have to use substring how can I improve this to work every time.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
for(int i = 0; i < 20; i++) {
if(word.charAt(i) == 'a') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'e') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'i') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'o') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'u') {word = word.substring(0, i) + word.substring(i++);}
if(word.charAt(i) == 'y') {word = word.substring(0, i) + word.substring(i++);}
System.out.println(word);
}
finalWord = word;
}
public String getWord()
{
return finalWord;
}
}

You can use the simplified code as below to do so:
public static void main(String[] args) {
String stringPara = "this example will remove the vowals aeiou";
stringPara = removeCharFromString(stringPara, "a");
stringPara = removeCharFromString(stringPara, "e");
stringPara = removeCharFromString(stringPara, "i");
stringPara = removeCharFromString(stringPara, "o");
stringPara = removeCharFromString(stringPara, "u");
System.out.println(stringPara);
}
public static String removeCharFromString(String str, String characterToRemove){
while(str.contains(characterToRemove)){
str = str.substring(0, str.indexOf(characterToRemove)) + str.substring(str.indexOf(characterToRemove)+1, str.length()) ;
}
return str;
}

Why won't you use a simple Regex?
String str = "Hello world!";
str = str.replaceAll("[AEIOUaeiou]", "");
The new value of str will be Hll wrld!

The problem is in your i++ operator. It messes up both your character checking as well as your loop. The post decrement operator (i++) takes the original value of i as method argument but increases its value by one for all subsequent instructions.
To illustrate this, let's assume the input is "Treyarch". Then, at index 2 the character at i is e. And the instruction
word = word.substring(0, i) + word.substring(i++); will have the following consequences:
word = Treyarch
i = 3
Not only does it not expel the vowel from the String it also messes up your index (i) . Because for the rest of the loop the i is 4 and when you enter the next iteration it will be 5, so your program never checks the first two if condition.
That being explained, the best practice for this solution would be to check for any of the conditions in one if statement and use immutable index. In other words:
for(int i = 0; i < word.length(); i++) {
if(word.charAt(i) == 'a' || word.charAt(i) == 'e' || word.charAt(i) == 'i' || word.charAt(i) == 'o' || word.charAt(i) == 'u' || word.charAt(i) == 'y') {
word = word.substring(0, i) + word.substring(i + 1);
}

You got a problem with your incrementation logic. When you remove a char, you missed the following one.
Your code could be easier to read if you use switch statements.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
// don't go too far !!
for (int i = 0; i < word.length(); i++) {
switch (word.charAt(i)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'y':
// remove this vowel
word = word.substring(0, i) + word.substring(i + 1);
// step back in order to analyse the new i-th char
i--;
}
System.out.println(word);
}
finalWord = word;
}
public String getWord() {
return finalWord;
}
}

public static void main(String[] args)
{
String WordsWithoutVowels ="mayank";
String updated="";
for(char char1: WordsWithoutVowels.toCharArray())
{
switch(char1)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
break;
default:
updated+=char1;
}
}
System.out.println(updated);
}

I fixed your original solution. First of all - iterate over each letters - to word.length(). Other problem was with increasing "i".
for (int i = 0; i < word.length(); ) {
if (word.charAt(i) == 'a') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'e') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'i') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'o') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'u') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
if (word.charAt(i) == 'y') {
word = word.substring(0, i) + word.substring(i+1);
continue;
}
i++;
System.out.println(word);
}
finalWord = word;
Here more elegant way:
public class WordsWithoutVowels {
String finalWord;
List<Character> vowels = Arrays.asList('a', 'e', 'i', 'o', 'u', 'y');
public WordsWithoutVowels(String word) {
for (int i = 0; i < word.length(); ) {
if (vowels.contains(word.charAt(i))) {
word = word.substring(0, i) + word.substring(i + 1);
continue;
}
i++;
System.out.println(word);
}
finalWord = word;
}
public String getWord() {
return finalWord;
}
}

simplified your solution to meet the requirement.
public class WordsWithoutVowels {
String finalWord;
public WordsWithoutVowels(String word) {
StringBuilder sb = new StringBuilder(word);
for(int i = 0; i < sb.length;) {
if(sb.charAt(i)=='a' || sb.charAt(i)=='e' || sb.charAt(i)=='i' || sb.charAt(i)=='o' || sb.charAt(i)=='u')
sb.deleteCharAt(i);
else
i++;
}
finalWord = sb.toString();
}
public String getWord()
{
return finalWord;
}
}

public WordsWithoutVowels(String word) {
for (int i = 0; i < 20; i++)
{
if (word.charAt(i) == 'a') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'e') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'i') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'o') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } else if (word.charAt(i) == 'u') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } if (word.charAt(i) == 'y') {
word = word.substring(0, i) + (i == 19 ? "" : word.substring(++i)); } System.out.println(word + " " + i);
} finalWord = word; }

Related

Next Character Check in Java

String input = "a == b";
for(int i = 0; i < input.length(); i++){
char c = input.charAt(i);
if(c == '='){
System.out.println("Assignment Operator");
}
}
In the above example if character is '=' and the next character is also '=' then print Comparison Operatorotherwise print Assignment Operator
You can do something like this
for(int i = 0; i < input.length() - 1; i++){
if(input.charAt(i) == '=') {
if(input.charAt(i + 1) == '=') {
System.out.println("Comparison Operator");
}
else {
System.out.println("Assignment Operator");
}
break;
}
}
The solution is simple:
if(input.charAt(input.indexOf("=") + 1) == '='){
System.out.println("Comparison Operator");}else{
System.out.println("Assignment Operator");
}
You can either use the strings class substring method, or the charAt method or you could use the contains these all would allow you to do what you want.

in function findVowels for loop increment doesn't work, only prints the last vowel?

here in the findVowels function I am trying to print every 2nd vowel which I got from outPut function in rev but it just print the last vowel only....
import java.util.Scanner;
public class VowelString {
static char rev;
static String str;
static int count = 0;
void inPut() {
Scanner sc = new Scanner(System.in);
str = sc.nextLine();
System.out.println(str);
sc.close();
}
void outPut() {
System.out.println(str);
// int length=str.length();
try {
for (int i = 0; i <= str.length() - 1; i++) {
if ((str.charAt(i) == 'a') || (str.charAt(i) == 'e')
|| (str.charAt(i) == 'i') || (str.charAt(i) == 'o')
|| (str.charAt(i) == 'u')) {
rev = str.charAt(i);
System.out.print(rev);
count++;
}
}
// System.out.println(rev);
System.out.println("\ntotal " + count);
} catch (IndexOutOfBoundsException e) {
System.out.println(e);
}
}
void findVowels(char word) {
this.rev = word;
String asta = String.valueOf(rev);
for (int i = 0; i <= asta.length() - 1; i = +2) {
char nawa = asta.charAt(i);
System.out.println("something = " + nawa);
}
}
public static void main(String[] args) {
VowelString vS = new VowelString();
vS.inPut();
// System.out.println("Values of Input " + vS);
vS.outPut();
// System.out.println("Values of OutPut " + vS);
vS.findVowels(rev);
}
}
You are only saving the last vowel you find to rev
rev = str.charAt(i);
inside output(). So rev in findVowel will only be 1 char it seems. Perhaps you mean to say
rev += str.charAt(i);
Though this is not recommendable in a general setting it will probably suffice for your problem unless you have huge Strings.
The posted code should print all vowels. Not only the last as you say. But also not every 2nd as you want. It's also poorly written. Here's one way to print every second vowel, and a bit better written overall:
for (int i = 0, count = 0; i < str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
if (count % 2 == 0) {
System.out.print(c);
}
break;
}
}

PigLatin program help...Capitalize?

I have the program working except for the capitalization part:
Here's how to translate the English word englishWord into the Pig Latin word pigLatinWord:
a. If there are no vowels in englishWord, then pigLatinWord is just englishWord + "ay". (There are ten vowels: 'a', 'e', 'i', 'o', and 'u', and their uppercase counterparts.)
b. Else, if englishWord begins with a vowel, then pigLatinWord is just englishWord + "yay".
c. Otherwise (if englishWord has a vowel in it and yet doesn't start with a vowel), then pigLatinWord is end + start + "ay", where end and start are defined as follows:
1. Let start be all of englishWord up to (but not including) its first vowel.
2. Let end be all of englishWord from its first vowel on.
3. But, if englishWord is capitalized, then capitalize end and "uncapitalize" start.
How do you do the capitalization part?
So far, I get Hasta= astaHay. It should be Hasta = Astahay
Here is the basic program so far:
public static boolean isVowel(char c) {
if (c == 'a' && c == 'A') {
return true;
} else if (c == 'e' && c == 'E') {
return true;
} else if (c == 'i' || c == 'I') {
return true;
} else if (c == 'o' || c == 'O') {
return true;
} else if (c == 'u' || c == 'U') {
return true;
} else {
return false;
}
}
public static String convertPigLatinWord(String englishWord) {
int length = englishWord.length();
if (englishWord.charAt(length - 1) == '.' && englishWord.charAt(length - 1) == '!' && englishWord.charAt(length - 1) == '?') {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1, length - 1);
return (rest + ch + "ay" + englishWord.charAt(length - 1) + "\"" + " ");
} else if (isVowel(englishWord.charAt(0))) {
return (englishWord + "yay" + " ");
} else {
char ch = englishWord.charAt(0);
String rest = englishWord.substring(1);
return (rest + ch + "ay" + " ");
}
}
public String translate() {
String pigLatinPhrase = "";
while (englishPhrase.length() > 1) {
String word = getWord();
pigLatinPhrase += convertPigLatinWord(word) + " ";
}
return pigLatinPhrase;
}
public static void main(String[] args) {
String answer = "";
do {
Scanner keyboard = new Scanner(System.in);
String input;
System.out.print("Please enter an English phrase: ");
input = keyboard.nextLine();
PigLatin3 first = new PigLatin3(input);
System.out.println(first.translate());
System.out.println("Would you like to translate another phrase? (y or n)");
answer = keyboard.nextLine();
} while (!(answer.equals("N")) && !(answer.equals("n")));
System.exit(0);
}
}
You can capitalize a letter by breaking the string to substrings and then capitalizing them:
String word = word.substring(0, 1).toUpperCase() + word.substring(1);
So just use the toUpperCase() and toLowerCase() methods of String ...
There is also a neat trick that you can use with single characters based on the ASCII table. Just xor them with 32 to get the other case.
What you are looking for is something like this:
public static String onlyFirstLetterUpperCase(String a){
int i;
for (i = 0; i < a.length(); i++){
if("AEIOUaeiou".indexOf(a.charAt(i)) != -1 )
break;
// indexOf looks for a char in a given string and returns its
// position or -1 if not found. So if this indexOf returns -1 I can be sure,
// that the character is not a vowel
}
return a.substring(0, i + 1).toUpperCase() + a.substring(i + 1).toLowerCase();
}
Just call this method after performing your operations

Taking vowels from string. Java

I'm having trouble with this simple exercise. What I have to do is to take the vowels from the string.
This returns all the vowels in the string, but what I want is that if there are multiple letters of same vowel, just return one.For example, using the string "aaa eee iii" should give "a e i".
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
I would recommend either adding each vowel found to a HashSet<Character>, or calling aString.contains() with each vowel in turn. You can also use aString.toLowerCase() so that you only have to check for lowercase vowels.
Edit your code as follows:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
EDIT :
Alternatively,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
Why are you doing for loop? Just check String.IndexOf() and if that character is present print it.
You need to have a string where you keep on adding unique vowels checking before hand whether it exists. The below program will clear your doubt.
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
You could use an integer array whose indexes are ASCII codes. When you see a vowel, check its count in the array. If the count is 0, print the vowel and increase the count. For example, 'a' would be stored in arr[97]:
public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}

My ArrayList (s) are just printing numbers

I'm trying to write a bit of code that takes a string and translates it like this;
1. Take the first letter and put it at the end of the word for every word
2. Find the first vowel and put a 'b' and then the vowel again
3. Do the same as #2 except for the last vowel
I think I have it sort of close but my output is all numbers. It doesn't even look like the address of where it's stored.
I hope this helps other people for the reason that they might be having the same problem with printing array lists in a return statement.
By the way, It's a huge code block...Sorry. The only reason I did that is so I didn't have to put both classes in here.
Here's the code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Experiment {
public static void main(String[] args){
String pre = "For every minute you are angry you loose sixty seconds of happiness.";
System.out.println(translate(pre));
}
public static String translate(String sentence){
String[] sentenceArray = sentence.split(" ");
List<String> sentenceList = new ArrayList<>();
List<String> finalList = new ArrayList<>();
String punctuation = getPunctuation(sentenceArray[sentenceArray.length - 1]);
//add all words but the last so i can take punctuation off it
for (int i = 0; i < sentenceArray.length - 1; i ++){
sentenceList.add(sentenceArray[i]);
}
//take the first letter off each word and put at at the end of each word
Arrays.asList(sentenceArray);
for (String el : sentenceArray)
sentenceList.add(firstToLast(el));
//use the addFrontB method on each word
Arrays.asList(sentenceList);
for (String la : sentenceList){
finalList.add(addFrontB(la));
}
//use the addBackB method on each word
Arrays.asList(sentenceList);
for (String le : sentenceList){
finalList.add(addBackB(le));
}
return finalList + punctuation + "\n";
}
//finds the last character of the last word which is punctuation
public static String getPunctuation(String word){
return word.charAt(word.length() - 1) + "";
}
//takes the punctuation off
public static String removePunctuation(String word){
String newWord;
newWord = word.substring(word.length(), word.length());
return newWord;
}
//puts the first letter at the end of the word
public static String firstToLast(String word){
char letter = word.charAt(0);
String newWord = word.substring(1,word.length()) + letter;
return newWord;
}
//insterts a b and then the same vowel behind the first vowel
public static String addFrontB(String word){
StringBuilder finishedWord = new StringBuilder();
for (int i = 0; i < word.length(); i ++){
if (word.charAt(i) == 'a')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'e')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'i')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'o')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
else if (word.charAt(i) == 'u')
finishedWord = finishedWord.append(word.charAt(i) + 'b' + word.charAt(i));
}
String newWord = finishedWord.toString();
return newWord;
}
//does the same as addFirstB but at the end of the word
public static String addBackB(String word){
StringBuilder finishedWord = new StringBuilder();
finishedWord.append(word);
finishedWord.reverse();
for (int i = 0; i < word.length(); i ++){
if (finishedWord.charAt(i) == 'a')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'e')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'i')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'o')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
else if (finishedWord.charAt(i) == 'u')
finishedWord.append(finishedWord.charAt(i) + 'b').reverse();
}
return finishedWord.toString();
}
}
Your mistake is here:
return finalList + punctuation + "\n";
Since you add "\n" with the plus operator, java calls the toString() method of your list, which returns nonsense. You have to iterate through the list and build your own string, best practice is to use StringBuffers.
return finalList + punctuation + "\n";
You are treating the List as if it were a string here.. Do you need to do .toString() or something similar?
asList(T... a)
Returns a fixed-size list backed by the specified array.
You are not using the return value either, of Arrays.asList

Categories