不知道如何操作字符串

将一个字符串作为输入 S。编写一个函数,将每个奇数字符替换为具有较高 ASCII 代码的字符,并将每个偶数字符替换为具有较低 ASCII 代码的字符。打印返回的值。


 package assignments;


 import java.util.Scanner;


 public class strings_odd_even_char {

     static Scanner scn = new Scanner(System.in);


     public static void main(String[] args) {

         String str = scn.nextLine();


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

             char ch = str.charAt(i);

             ch = (char)((ch + 1));

             System.out.println(ch);

         }

         for (int j = 1; j < str.length(); j = j + 2) {

             char ch = str.charAt(j);

             ch = (char)((ch - 1));

             System.out.print(ch);

         }


     }


 }

我的代码的问题在于它首先打印所有奇数字符的值,然后打印偶数字符,但我想要的是它们以正确的顺序打印,例如输入 --> abcg ,输出应该是 -->坏的。


拉丁的传说
浏览 159回答 3
3回答

千万里不及你

您只需要迭代一次但执行不同的操作(char+1)或(char-1)取决于i:public static void main(String[] args) {&nbsp; &nbsp; String str = scn.nextLine();&nbsp; &nbsp; for(int i = 0; i < str.length(); i++) {&nbsp; &nbsp; &nbsp; &nbsp; char ch = str.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; if(i % 2 == 0) { // even&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ch += 1;&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// odd&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ch -= 1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(ch);&nbsp; &nbsp; }}

精慕HU

只需使用一个循环来处理这两个字符:for (int i = 0; i < str.length(); i = i + 2) {&nbsp; char ch = str.charAt(i);&nbsp; ch = (char) (ch + 1);&nbsp; System.out.print(ch);&nbsp; if (i + 1 < str.length()) {&nbsp; &nbsp; ch = str.charAt(i + 1);&nbsp; &nbsp; ch = (char) (ch - 1);&nbsp; &nbsp; System.out.print(ch);&nbsp; }}

幕布斯7119047

我将“incremenet”值保存在一个变量中,+1并-1在我访问字符时交替使用:private static String change(String s) {&nbsp; &nbsp; StringBuilder sb = new StringBuilder(s.length());&nbsp; &nbsp; int increment = 1;&nbsp; &nbsp; for (int i = 0; i < s.length(); ++i) {&nbsp; &nbsp; &nbsp; &nbsp; sb.append((char)(s.charAt(i) + increment));&nbsp; &nbsp; &nbsp; &nbsp; increment *= -1;&nbsp; &nbsp; }&nbsp; &nbsp; return sb.toString();}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java