简体   繁体   中英

Char to Int, change int value, back to char, and add to a string

I feel that I am extremely close to solving this issue. Provided a string, I want to convert the char from the string to an int, add a value from another method ( getKey ) to this number, and if the result is greater than 26, subtract 26. Then, convert this new int to its char , and finally place that char at the end of a string . As of now it simply returns the input with spaces subtracted, which is half way there haha. Interestingly, replacing

msg.replace(msg.charAt(i), btc);   // from the bottom

with

msg += btc;

initiates an infinite loop. Any advice would be tremendously appreciated!

    String msg = "";
    int key;
    int cnum;
    for(int i = 0; i< message.length();i++){
        if(Character.isLetter(message.charAt(i))){
            msg += (message.charAt(i));
        }
    }



    for(int i = 0; i< msg.length(); i++){  

        char ch = msg.charAt(i);
        key = getKey();

            cnum = (int)ch + key;
            if(cnum > 26){
                cnum -= 26;
            }

        char btc = (char)cnum;
        msg.replace(msg.charAt(i), btc);
    }

return msg;

Replace msg.replace(msg.charAt(i), btc); with msg = msg.replace(msg.charAt(i), btc);

Your problem is at line

msg.replace(msg.charAt(i), btc);

As String is immutable, String.replace() will return a new string and not modify the existing String.

I would suggest you use a StringBuilder(), append the replaced character or append the existing char.

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