【问题标题】:How to replace the value of the index of a string in an array如何替换数组中字符串的索引值
【发布时间】:2014-11-16 00:25:21
【问题描述】:

我正在做一个关于图灵机的项目,但我遇到了如何替换字符串某个索引中的字符的问题

示例:如果我在初始磁带中输入: 堆栈溢出 然后在 inputArea 中编码,如 写 1 输出应该是 1tackoverflow 但遗憾的是我的代码的输出是 11111111111111

我正在尝试摆脱循环,因为我知道我的循环是问题,但我应该怎么做呢?

这是我的代码

runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ActE){

    String[] iniTape = iTapeArea.getText().split("");


    String[] input = inputArea.getText().split("\n");
    for(int i=0;i<input.length;i++)
    {
        if(input[i].contains("write")==true){
            sub = input[i].substring(6, input[i].length());
             for(int j=0;j<iniTape.length;j++){
        System.out.print(""+iniTape[j].replace(iniTape[j], sub));

            }
        }
    }
}

});

【问题讨论】:

    标签: java arrays for-loop split


    【解决方案1】:

    没有必要这么努力。你可以使用

     String str = "stackoverflow";
     System.out.println(str.replace("" + str.charAt(0), "1"));
    

    输出:

     1tackoverflow
    

    【讨论】:

    • 是的,先生,它可以这么简单,但例如,如果我编写代码 write 1 write 2 write 3 输出应该是 123ckoverflow
    • @marky 您正在提供这样的输入吗? “写1写2写3”还是“1 2 3”???
    【解决方案2】:

    如下使用String类replaceAll()方法

    yourString.replaceAll("" + yourString.charAt(index), "1")//index is your index at which you want to replace
    

    ""+ 相当于做String.valueOf(yourString.charAt(index))

    【讨论】:

      【解决方案3】:

      这可能会解决问题

      String[] iniTape = iTapeArea.getText().split("");
      String sub= null;
      String temp = null;
      String[] input = inputArea.getText().split("\n");
      //"test 1\ntest 2\ntest 3".split("\n");
      for(int i=0;i<input.length;i++)
      {
          if(input[i].contains("write")==true){
              sub = input[i].substring(6, input[i].length());
                iniTape[i+1] = sub;
          }
      }
      StringBuffer buffer = new StringBuffer();
      for(String str : iniTape) {
        buffer.append(str);
      }
      System.out.println(buffer.toString());
      

      用需要的字符替换索引值

      【讨论】:

        【解决方案4】:

        我使用String类的replaceFirst(String, String)函数。

        public static void main(String[] args) {
            String s = "stackoverflow";
            s = s.replaceFirst("" + s.charAt(0), "1");
            System.out.println(s);
        }
        

        【讨论】:

          【解决方案5】:

          如果您想用该数字替换字符串的给定某些索引,您可以执行以下操作

          static String str = "stackoverflow";
          public static String replaceCharsAt(int ... indices) {
              for (int index : indicies) {
                  str = str.replace(str.charAt(i), i+1);
              }
              return str;
          }
          

          【讨论】:

            猜你喜欢
            • 2021-08-25
            • 1970-01-01
            • 1970-01-01
            • 2022-01-03
            • 2016-12-15
            • 1970-01-01
            • 2015-12-25
            • 2021-10-01
            • 1970-01-01
            相关资源
            最近更新 更多