且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在for循环中添加到ASCII代码

更新时间:2022-06-02 22:28:54

简单:

sentence.charAt(i) += (char)x;

您错误地认为charAt()给您带来了左手侧"的麻烦.换句话说:您可以分配一个值的东西;像一个变量.

You wrongly assume that charAt() gives you a "left hand side" thingy. In other words: something that you can assign a value to; like a variable.

但这是不可能的:charAt()返回一个char值;表示该索引处字符串中的char.

But this is not possible: charAt() returns an char value; that represents the char within the string at that index.

它确实为您提供了一些使您可以操纵字符串本身的东西!字符串是不可变的.您不能使用charAt()修改其内容!

It does not give you something that allows you to manipulate the string itself! Strings are immutable; you can't use charAt() to modify its content!

换句话说;您可以这样做:

In other words; you can do this:

char c = 'a';
c += 'b';

但是您不能使用charAt()来达到相同的效果!

but you can't use charAt() to achieve the same!

因此,为了使代码正常工作,您必须构建一个 new 字符串,例如:

Thus, in order to make your code work, you have to build a new string, like:

StringBuilder builder = new StringBuilder(sentence.length());
for(int i = 0; i < sentence.length(); i++) {
  if(sentence.charAt(i) >= 65 && sentence.charAt(i) <= 90){
    int x = (int)sentence.charAt(i);
    x += key;
    while(x > 90){
      x = x - 26;
    }
    builder.append(sentence.charAt(i) + (char)x));
  } else {
    builder.append(sentence.charAt(i)); 
  }
}

(免责声明:我刚刚写下了上面的代码;其中可能有错别字或小错误;这是为了让您使用伪代码"!)

(disclaimer: I just wrote down the above code; there might be typos or little bugs in there; it is meant to be "pseudo code" to get you going!)

除此之外:我找到了该方法的名称;以及它如何处理该布尔字段...有点令人困惑.您会发现,如果加密为 true ... ...该方法没有执行任何操作?!然后,它不会切换"任何内容.因此,这个名字确实令人误解.与您的代码不匹配!

Beyond that: I find the name of that method; and how it deals with that boolean field ... a bit confusing. You see, if encryption is true ... the method does nothing?! Then it doesn't "toggle" anything. Thus that name is really misleading resp. not matching what your code is doing!