user6279422
user6279422

Reputation: 19

Replace consonants in a string with next consonant in alphabet

Here I am trying to input a string and compare the string letters to consonant string letters. When the input letter and consonant matches then output should print next letter of consonant.

Example:: input = java
         output = kawa  

here j and v are consonant so next letter after j is k, likewise after v we have w.

BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter any string = ");
String inputString = bf.readLine().toLowerCase();

for(int i=0; i < inputString.length(); i++){
    inputChar = inputString.charAt(i);

    String consonants = "BCDFGHJKLMNPQRSTVWXYZ".toLowerCase();
    for(int j = 0; j < consonants.length(); j++){
        stringChar = consonants.charAt(j);

        if(inputChar == stringChar){
        }  

    }
}

Upvotes: 4

Views: 9631

Answers (4)

Kajal
Kajal

Reputation: 739

 //declare out side of the loop
 String consonants = "BCDFGHJKLMNPQRSTVWXYZ".toLowerCase();
 //initialize the result
 String op = "";

 for(int i=0; i < inputString.length(); i++){
     inputChar = inputString.charAt(i);
     //find the index of char 
     int index = consonants.indexOf(inputChar);
     //if char 'z' then point to 'b' or to the next char
     op += index==-1 ? inputChar : consonants.charAt(index == consonants.length()-1  ? 0 : index+1);
 }
System.out.println(op);

Upvotes: 0

Andreas
Andreas

Reputation: 159135

The other two answers produce the right output, but they are not very efficient, so here is my take.

Your consonants should be a constant, and should be simply given as lowercase letters. As a constant, it should be named in uppercase (CONSONANTS).

To do a character-for-character replacement, the most efficient way is to get the char[] of the original string using toCharArray(), the modify the array, and create a new string using new String(char[]).

The easiest way to find the index of a letter in the CONSONANTS constant, is to use the indexOf() method.

To prevent overflow when adding 1 to the index, use the modulus operator (%).

private static final String CONSONANTS = "bcdfghjklmnpqrstvwxyz";

private static String shiftConsonants(String input) {
    char[] chars = input.toLowerCase().toCharArray();
    for (int i = 0; i < chars.length; i++) {
        int idx = CONSONANTS.indexOf(chars[i]);
        if (idx != -1)
            chars[i] = CONSONANTS.charAt((idx + 1) % CONSONANTS.length());
    }
    return new String(chars);
}

Test:

System.out.println(shiftConsonants("Java")); // prints: kawa

Here is an alternate solution that retains the original case.

private static final String CONSONANTS = "bcdfghjklmnpqrstvwxyz";
private static String shiftConsonants(String input) {
    char[] chars = input.toCharArray();
    for (int i = 0; i < chars.length; i++) {
        char ch = chars[i];
        char lower = Character.toLowerCase(ch);
        int idx = CONSONANTS.indexOf(lower);
        if (idx != -1) {
            char next = CONSONANTS.charAt((idx + 1) % CONSONANTS.length());
            chars[i] = (ch == lower ? next : Character.toUpperCase(next));
        }
    }
    return new String(chars);
}

Test:

System.out.println(shiftConsonants("Java")); // prints: Kawa

Follow-up to comment by @MistahFiggins:

Would casting to int for each character and then modifying the number and casting back be more or less efficient?

My guess was wrong. For the lowercase version (first one above), numeric increment is 36% faster.

private static String shiftConsonants(String input) {
    char[] chars = input.toLowerCase().toCharArray();
    for (int i = 0; i < chars.length; i++) {
        char ch = chars[i];
        if (ch == 'z')
            chars[i] = 'b';
        else if (ch >= 'b' && ch <= 'y' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
            ch = (char)(ch + 1);
            if (ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
                ch++;
            chars[i] = ch;
        }
    }
    return new String(chars);
}

As you can see, it's optimized to not even consider a.

Upvotes: 3

Pritam Pallab
Pritam Pallab

Reputation: 68

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class TestIt {

    public static void main(String args[]) throws IOException
    {
        List<Character> consonantList = new ArrayList<Character>();
        consonantList.addAll(Arrays.asList('b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        char[] userInput = bufferedReader.readLine().toLowerCase().toCharArray();
        for(int i=0;i<userInput.length;i++)
        {
            if(consonantList.contains(userInput[i]))
            {
                userInput[i]=consonantList.get((consonantList.indexOf(userInput[i])+1)%21);
            }
        }
        System.out.println(String.valueOf(userInput));
    }
}

Upvotes: 0

Michael Markidis
Michael Markidis

Reputation: 4191

String consonants = "BCDFGHJKLMNPQRSTVWXYZ".toLowerCase();

String inputString = "java";

String retStr = "";

inputString = inputString.toLowerCase();

for(int i=0; i < inputString.length(); i++)
{
     char inputChar = inputString.charAt(i);

     int indexOfCons = consonants.indexOf(inputChar);

     if (indexOfCons != -1)
     {
           indexOfCons++;

           // if the letter is Z, then go around to B
           if (indexOfCons == consonants.length())
           {
                indexOfCons = 0;
           }
           retStr += consonants.charAt(indexOfCons);
     }
     else
     {
           retStr += inputChar;
     }
}
System.out.println(retStr);

Outputs:

kawa

Upvotes: 1

Related Questions