简体   繁体   English

保留单词java之间的空格

[英]Preserve space between words java

I have a method with two inputs. 我有一个带两个输入的方法。 The problem is when I type something like fast car.When it returns the message after the calculations I will get idvwfdu it gets rid of the space between the two words, but I want idvw fdu. 问题是当我输入类似快车的东西时。当它在计算后返回消息时我会得到idvwfdu它摆脱了两个单词之间的空格,但我想要idvw fdu。 How can I fix that? 我该如何解决这个问题?

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

       if (character >='a' && character <='z'){

          newMsg+=character;

       }else if(character > 'z') {

          newMsg+=(char)((char)(c-(26-shift)));
       }


}

return newMsg;

There are two issues with your code. 您的代码有两个问题。 First one is that you are shifting every character before checking like here 首先,你要在检查之前转移每个角色

char character=(char)(c+shift); // you already lost space character here

and secondly you are losing the space here 其次你在这里失去了空间

if (character >='a' && character <='z'){

     newMsg+=character;

   }else if(character > 'z') { // space will be shifted once again

      newMsg+=(char)((char)(c-(26-shift)));
   }

So in order to fix this you have to keep both evaluation in mind and the result should look like this 所以为了解决这个问题,你必须记住两个评估,结果应该是这样的

String text = "fast car";
String newMsg = "";
int shift = 1;
for (int i = 0; i < text.length(); i++) {
      char c = text.charAt(i);
      char character = (char)(c != ' ' ? c + shift : c); // first space check

      if (character >= 'a' && character <= 'z') {

          newMsg += character;

      } else if (character == ' ') newMsg += ' '; // second space check
      else if (character > 'z') {

          newMsg += (char)((char)(c - (26 - shift)));
      }

System.out.println(newMsg); // prints gbtu dbs

If your concern is just about the space not being preserved, 如果你关心的是没有保留的空间,

Replace 更换

if (character >='a' && character <='z'){

with

if ((character >='a' && character <='z') || character == ' '){

Add a condition for the space character in for loop and continue. 在for循环中添加空格字符的条件并继续。

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

   char c=text.charAt(i);

   if( c== ' '){
       newMsg+=c;
       continue;
    }
  ......

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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