如何替换数组中字符串索引的值

时间:2014-09-22 05:38:17

标签: java arrays for-loop split

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

示例:如果我在初始磁带中输入: 堆栈溢出 然后在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));

            }
        }
    }
}

});

5 个答案:

答案 0 :(得分:0)

无需努力尝试。你可以使用

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

Out put:

 1tackoverflow

答案 1 :(得分:0)

使用 String类 replaceAll()方法,如下所示

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

“”+ 相当于执行String.valueOf(yourString.charAt(index))

答案 2 :(得分:0)

这可能会成功

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());
     

用所需的字符

替换索引值

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

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

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