Megan Majewski
Megan Majewski

Reputation: 11

Java Letter changes arraylist to string without commas but including white spaces

Trying to complete this challenge from coderbyte: "Using the Java language, have the function LetterChanges(str) take the str parameter being passed and modify it using the following algorithm. Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string."

The problem that i am having is the replace is pulling on the white spaces between characters, but I need it to preserve white spaces between words. Is there a better solution to this?

import java.util.Arrays;
import java.util.Scanner;

public class nextLetter {
    public static String LetterChanges(String str) {
        String[] inputString = str.replaceAll("[^a-zA-Z ]", "").split("");
        String[] alph= "abcdefghijklmnopqrstuvwxyz".split("");
        String[] vowel ="aeiouy".split("");
        for(int i=0; i<inputString.length; i++){
            int index= Arrays.asList(alph).indexOf(inputString[i])+1;
            inputString[i]= alph[index];
            if(Arrays.asList(vowel).indexOf(inputString[i])>0){
                inputString[i]= inputString[i].toUpperCase();
            }
        }
        //System.out.println(Arrays.toString(inputString));
        return Arrays.toString(inputString)
                .replace(" ","")
                .replace(",", "")  //remove the commas
                .replace("[", "")  //remove the right bracket
                .replace("]", "")//remove the left bracket
                .replace(" ","")
                .trim();
    }
    public static void main(String[] args) {
     Scanner s = new Scanner(System.in);
     System.out.println("enter a sentence");
     System.out.print(LetterChanges(s.nextLine())); 
}
}

Also I would not mind any pointers on how to improve this!

Upvotes: 0

Views: 492

Answers (3)

Marco A. Hernandez
Marco A. Hernandez

Reputation: 821

If have fixed alphabeth and swapping algorithm you can use a static dictionary.

public static HashMap<String,String> dictionary = new HashMap<>();

    static{
        dictionary.put(" ", " ");
        dictionary.put("a", "b");
        dictionary.put("b", "c");
        dictionary.put("c", "d");
        dictionary.put("d", "E");
        .
        .
        dictionary.put("z", "A");
    }

    public static  String shiftLetters(String str){         
        StringBuffer response = new StringBuffer();

        for (int i = 0; i < str.length(); i++){
            response.append(dictionary.get(String.valueOf(str.charAt(i))));
        }

        return response.toString();
    }   

Upvotes: 0

Michael
Michael

Reputation: 2773

Note: I've changed the method name to something a bit more descriptive. The method assumes that you're only working with lowercase letters.

public static void main(String[] args){
    System.out.println(shiftLetters("abcdz")); //bcdea
}

public static String shiftLetters(String str){
    StringBuilder shiftedWord = new StringBuilder();

    for (int i = 0; i < str.length(); i++){
        char currentChar = str.charAt(i);
        if (currentChar != ' '){
            currentChar += 1;
            if (currentChar > 'z'){
                currentChar = 'a';
            }
        }
        shiftedWord.append(currentChar);
    }

    return shiftedWord.toString();
}

This is the general logic flow of this program: create a cumulative StringBuilder object that will eventually be the return value of the method. Loop through all characters in the string; if the character is a whitespace character, then simply don't bother with it and add it onto the StringBuilder as is. Else, add one to the current character. Note that chars are an integral(4.2.1) primitive type, so you may add ints to a char as such. If it's the special case that the new char is out of the normal a-z range, set it back to a.

Taking Use of Java 8's API

public static String functionalShiftLetters(String str){
    return str
        .chars()
        .map(c -> c != ' ' ? c + 1 : c)
        .map(c -> c > 'z'? 'a' : c)
        .collect(StringBuilder::new,
                   StringBuilder::appendCodePoint, StringBuilder::append)
        .toString();
}

Upvotes: 2

Michael Markidis
Michael Markidis

Reputation: 4191

This preserves all other characters and handles the vowels.

public static String LetterChanges(String str)
{
    str = str.toLowerCase();
    StringBuilder sb = new StringBuilder();

    for (int i = 0; i < str.length(); i++)
    {
        char c = str.charAt(i);

        if ('a' <= c && c <= 'z')
        {
            c = (c == 'z') ? 'a' : (char) (c + 1);

            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
            {
                c = Character.toUpperCase(c);
            }
        }
        sb.append(c);
    }
    return sb.toString();
}

Input: abcdefghijklmnopqrstuvwxyz 1234567890

Output: bcdEfghIjklmnOpqrstUvwxyzA 1234567890

Upvotes: 1

Related Questions