当前位置: 动力学知识库 > 问答 > 编程问答 >

java - i want replace fourth character of each element of the string arraylist with the other character

问题描述:

list2.get(i).replace(list2.get(i).charAt(4), list3.get(i));

list2 is the string arraylist, for example [00110001, 11111111, 00000000,

01001010, 00000000]

I want to replace 4th character of each element in list2, that replacing

character store in list3 so it will contain [1, 0, 1, 1, 1]

Finally my arraylist list2 should look like [00111001, 11110111, 00001000, 01001010, 00001000].

网友答案:

First, you have to note that String is immutable. This means that you can't do this just by running any method on list2.get(i). All string methods return new string values, but do not change the values of the original string.

So you have to use list2.set( i, newValue ) to replace the previous string with a new string that you will construct.

Now, how do you construct value? You take the parts of the string that are not supposed to change, and stick the new character value between them:

Something like:

String oldValue = list2.get(i);
String newValue = oldValue.substring(0,3) + list3.get(i) + oldValue.substring(5);
网友答案:

You could do it something like:

  • Define a counter variable to be index of element in list3 starting 0.
  • Iterate over each element in the list2
  • Remove the string given by the iterator and convert it to charArray using toCharArray api on String
  • now change the bit using 4th index in char array using list3's element pointed by counter.
  • Convert char array back to String (using String(char[]) constructor) and add it to the list 2.
  • increment the counter.
分享给朋友:
您可能感兴趣的文章:
随机阅读: