简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM