[英]How to replace the value of the index of a string in an array
i am making a project about turing machine and i am having a problem about the how do i replace a character in an certain index of a string 我正在做一个关于图灵机的项目,而我在如何替换字符串的某个索引中的字符时遇到问题
Example: if i input in the initial tape: stackoverflow then code in the inputArea like write 1 the output should be 1tackoverflow but sadly the output of my code is 11111111111111 示例:如果我在初始磁带中输入:stackoverflow然后在inputArea中编写类似写1的代码,则输出应为1tackoverflow,但可悲的是,我的代码的输出为11111111111111
I'm trying to get rid of the loop because i know my loop is the problem but how should i do it ? 我试图摆脱循环,因为我知道我的循环是问题,但我应该怎么做?
Here's my code 这是我的代码
runButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ActE){ 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));
}
}
}
}
});
No need to try this hard. 无需为此努力。 You can use
您可以使用
String str = "stackoverflow";
System.out.println(str.replace("" + str.charAt(0), "1"));
Out put: 输出:
1tackoverflow
Use replaceAll() method of String class as below 使用String类的 replaceAll()方法,如下所示
yourString.replaceAll("" + yourString.charAt(index), "1")//index is your index at which you want to replace
""+ is equivalent of doing String.valueOf(yourString.charAt(index))
“” +等同于执行
String.valueOf(yourString.charAt(index))
This might do the trick 这可能会解决问题
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());
replace the index value with the required character
用所需的字符替换索引值
I use the replaceFirst(String, String) function of the String class. 我使用String类的replaceFirst(String,String)函数。
public static void main(String[] args) {
String s = "stackoverflow";
s = s.replaceFirst("" + s.charAt(0), "1");
System.out.println(s);
}
If you want to replace a given certain indexes of a string with that number you can do the following 如果要用该数字替换字符串的给定某些索引,可以执行以下操作
static String str = "stackoverflow";
public static String replaceCharsAt(int ... indices) {
for (int index : indicies) {
str = str.replace(str.charAt(i), i+1);
}
return str;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.