[英]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
.提供一个字符串,我想将字符串从字符串转换为 int,将另一个方法 (
getKey
) 的值添加到该数字,如果结果大于 26,则减去 26。然后,将此新int
转换为其char
,最后将该char
放在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);
替换
msg.replace(msg.charAt(i), btc);
with msg = 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); msg.replace(msg.charAt(i), btc);
As String is immutable, String.replace() will return a new string and not modify the existing String.由于 String 是不可变的,因此 String.replace() 将返回一个新字符串而不是修改现有的 String。
I would suggest you use a StringBuilder(), append the replaced character or append the existing char.我建议您使用 StringBuilder(),附加替换的字符或附加现有的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.