【问题标题】:Why isn't my certain part of the input being replaced with the corresponding char? [duplicate]为什么我输入的某些部分没有被相应的字符替换? [复制]
【发布时间】:2013-10-13 19:10:36
【问题描述】:

顺便说一句,我是一个初学者程序员,所以我真的不知道该怎么做。这是我尝试过的,但它只是打印出输入而没有替换字母。

  import java.util.Scanner;

  class converter {
  public static void main (String [] args){
  char[][] convert = new char [2][10];
  convert [0][0] = 'I' ;
  convert [0][1] = 'Z' ;
  convert [0][2] = 'E' ;
  convert [0][3] = 'A' ;
  convert [0][4] = 'S' ;
  convert [0][5] = 'G' ;
  convert [0][6] = 'L' ;
  convert [0][7] = 'B' ;
  convert [0][8] = 'P' ;
  convert [0][9] = 'O' ;
  convert [1][0] = '1' ;
  convert [1][1] = '2' ;
  convert [1][2] = '3' ;
  convert [1][3] = '4' ;
  convert [1][4] = '5' ;
  convert [1][5] = '6' ;
  convert [1][6] = '7' ;
  convert [1][7] = '8' ;
  convert [1][8] = '9' ;
  convert [1][9] = '0' ;

     Scanner sc = new Scanner(System.in);

     String input = sc.nextLine();
     for (int i = 0; i< 10; i++)
        input.replace(convert[0][i], convert [1][i]);
     System.out.print(input);

     }
   }

【问题讨论】:

  • 字符串是不可变的,也就是说你不能改变它,也就是说input.replace(convert[0][i], convert [1][i]);input没有影响。但是,replace 方法将返回一个带有更改的新字符串,如果您将此字符串分配给另一个字符串引用,甚至是 input 引用,您会看到您的更改。

标签: java replace char


【解决方案1】:

试试:

input = input.replace(convert[0][i], convert [1][i]);

Java 中的字符串是 immutable(不能修改),replace 方法不会影响您调用它的变量,但会返回一个带有所做更改的新字符串。

【讨论】:

    【解决方案2】:

    String.replace() 函数只返回一个新字符串,而不影响调用它的字符串。将input.replace(convert[0][i], convert [1][i]); 更改为input = input.replace(convert[0][i], convert [1][i]);

    【讨论】:

      【解决方案3】:

      您误解了 input.replace 到底在做什么!。它创建新字符串,在新字符串中替换它,然后用替换字符返回新字符串。

      这是你需要做的:

      input = input.replace(convert[0][i], convert [1][i]);
      

      【讨论】:

        猜你喜欢
        • 2022-06-13
        • 1970-01-01
        • 1970-01-01
        • 2011-12-31
        • 2018-04-08
        • 1970-01-01
        • 1970-01-01
        • 2017-08-30
        • 1970-01-01
        相关资源
        最近更新 更多