I am interested in iterating through (re: find and replace purposes),
say:
List<String> someList = new ArrayList<String>();
where someList is already populated in an earlier method,
and consists of, say just a couple elements, in the fashion of,
call it [a:bX, b:Xc],
where the find-and-replace String(s) of interest are, say:
String someString = "X";
String otherString = "Y";
String contentsTBD = "";
Now, ideally I thought I could’ve iterated over someList like so:
public void readAndReplace() {
for (int i = 0; i < someList.size(); i++) {
if (someList.get(i).contains(someString)) {
someList.get(i).replace(someString, otherString);
} else {
++i;
}
}
System.out.print(someList);
}
wherein the printout should read:
[a:bY, b:Yc]
Then, I thought this might work:
public void readAndReplace() {
for (String s : someList) {
contentsTBD += s;
}
for (int i = 0; i < contentsTBD.length(); i++) {
if (contentsTBD.contains(someString)) {
contentsTBD.replaceAll(someString, otherString);
} else {
++i;
}
}
System.out.print(contentsTBD);
}
but then quickly realized that this was nonsensical since
my reference to i was lost. Any advice would be really helpful.
Thank you.
First, you are not storing your Replaced String anywhere. It is gone with the wind.
Second, your replace will not modify the existing list. You would need to set the new string into the existing location, since you are using traditional for-loop. Or, you can have a new list, and
addmodified values to that list.Remember, since
Stringin Java is immutable, so all the methods of String class return a new string. They do not modify the existing one. So, you need to re-assign the returned String into a new one.Try out this code: –