简体   繁体   中英

letter change, what am I doing wrong?

So im trying the following challenge: Using the Java language, have the function LetterChanges(str) take the str parameter being passed andmodify it using the following algorithm. Replace every letter in the string with the letter following it in thealphabet (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.

This is my code

class LetterChange {  
  public static String LetterChanges(String str) {
    String alphabet = "AbcdEfghIjklmnOpqrstUvwxyz";
    char currentChar,letter;
    int i = 0;
    while (i < str.length())
    {
      currentChar = str.charAt(i);
      for(int x = 0; x < alphabet.length(); x++)
      {
        letter = alphabet.charAt(x);
        if (currentChar == letter){
          str  = str.replace(currentChar,alphabet.charAt(x+1));
          i++;
        }
      }
    }

when I run it it is returning the last char in string +1 letter in alphabet. for example if i was to run "bcd" it returns "EEE". I dont understand why its replacing all chars with the result of the loop for the last char.

Does this solution help?

public static String letterChanges(String str) {
    String alphabet = "AbcdEfghIjklmnOpqrstUvwxyz";

    StringBuilder stringBuilder = new StringBuilder();

    for (char letter : str.toCharArray()) {
        if (alphabet.contains(Character.toString(letter))) {
            int index = alphabet.indexOf(letter) + 1;

            if (index >= 26) {
                index = 0;
            }

            stringBuilder.append(alphabet.charAt(index));
        }
    }

    return stringBuilder.toString();
}

The previous solution was hard to follow, so it's difficult to explain why it wasn't working without debugging through it to see where it goes wrong. It was easier to use a for-each loop to go through the str parameter and find matches using Java's provided methods like .indexOf and .charAt.

Also, Java uses lower camel case method naming, letterChanges instead of LetterChanges :)

Let me know if you have any questions.

When you go through the loop the first time you get

"bcd"--> "ccd"

Now, str.replace will turn this into "ddd" on next turn, then "EEE". Ie, replace replaces every occurrence on each turn.

It is true that debugging it in the IDE will help you in the future! Also, what if you had a lowercase vowel in your string?

 public class Alphabet {

          public static String LetterChanges(String str) {
            String alphabet = "AbcdEfghIjklmnOpqrstUvwxyz";


            char[] string = str.toLowerCase().toCharArray();
            for (int i=0; i < string.length; i++) {
                char d = alphabet.charAt(((alphabet.toLowerCase().indexOf(string[i]))+1) % 26);

                string[i]=d;
            }

            return new String(string);
          }    
    public static void main(String[] args) {
        System.out.println(Alphabet.LetterChanges("aabb"));


    }       
}

alphabet.charAt(

((alphabet.toLowerCase().indexOf(string[i]))

+1) % 26)

1) use toLowerCase on the input and your string map to eliminate case problems

2) find character at index+1 in string map 'alphabet', treating it as a circular buffer using a modulus that takes z to a.
index 25 (z) + 1 == 26 --> 0 (A) because 26 is 0 mod 26 while index 0(A) + 1 = 1 --> 1 mod 26. It is only necessary to wrap the z to A while not changing the other 25 indices and is more efficient than branching with an "if" statement.

You are getting that result because on every replacing you are re-setting the input string. I recommend you:

  • Better try with two different variables: Let the input variable be unmodified, and work on the output one.
  • Since strings are unmodifiable -as you already know- better declare them as arrays of char.
  • For the shake of optimization, base your algorithm on one single loop , which will iterate over the characters of the input string. For each character, decide if it is alphabetic or not, and in case it is, what character should it be replaced with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM