Oce*_*tXL 8 java regex string parsing arraylist
我有兴趣迭代(re:查找和替换目的),说:
List<String> someList = new ArrayList<String>();
Run Code Online (Sandbox Code Playgroud)
someList已经在早期的方法中填充了,并且只包含几个元素,称之为[a:bX,b:Xc],
感兴趣的查找和替换字符串,例如:
String someString = "X";
String otherString = "Y";
String contentsTBD = "";
Run Code Online (Sandbox Code Playgroud)
现在,理想情况下我认为我可以像这样迭代someList:
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);
}
Run Code Online (Sandbox Code Playgroud)
其中打印输出应为:
[a:bY, b:Yc]
Run Code Online (Sandbox Code Playgroud)
然后,我认为这可能有效:
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);
}
Run Code Online (Sandbox Code Playgroud)
但后来很快意识到这是荒谬的,因为我对我的提及已经丢失了.任何建议都会非常有用.谢谢.
首先,您不会将替换字符串存储在任何位置.随风而逝.
其次,您的替换不会修改现有列表.您需要将新字符串设置为现有位置,因为您使用的是传统的for循环.或者,您可以拥有一个新列表,并将add
修改后的值添加到该列表中.
请记住,因为String
在Java中是不可变的,所以String类的所有方法都返回一个新字符串.他们不会修改现有的.因此,您需要将返回的String重新分配给新的String.
试试这段代码: -
public void readAndReplace()
{
// You can also create a new list out of the existing list.
// That way, you won't need to modify the existing one.
List<String> newList = new ArrayList<String>();
for(int i = 0; i < someList .size(); i++)
{
if(someList.get(i).contains(someString))
{
newList.add(someList.get(i).replace(someString, otherString));
//someList.set(i, someList.get(i).replace(someString, otherString));
} else {
// If it not contains `someString`, add it as it is to newList
newList.add(someList.get(i));
}
}
System.out.println(someList); // Original
System.out.println(newList); // New List
}
Run Code Online (Sandbox Code Playgroud)
在MadProgrammer的建议之后编辑了补充说明,
第1点:String
是Immutable
,并且您正在尝试使用它来修改字符串someList.get(i).replace(someString, otherString);
,但不能反映在您的内部someList
,以反映您必须调用的someListsomeList.set(i)
第2点:你的else
区块是无用的,因为你已经incrementing
在i
里面了for loop
试试这个.
String oldStr="";
for (int i = 0; i < someList.size(); i++) {
if (someList.get(i).contains(someString)) {
oldStr = someList.get(i).replace(someString, otherString);
someList.set(i, oldStr);
}
}
System.out.print(someList);
Run Code Online (Sandbox Code Playgroud)
看到在java中如何不可改变的工作不变
小智 5
我知道这个问题很老了,但我只是在寻找同样的东西,并且认为我会为了别人而添加我发现的东西.
我发现这样做的最简单方法是使用ListIterator类,它是Iterator的子接口,专门用于列表.它使这种操作非常简单:
public void replace(List<String> list) {
ListIterator<String> it = list.listIterator();
while(it.hasNext()) {
it.set(it.next().replace("old_text","new_text"));
}
}
Run Code Online (Sandbox Code Playgroud)
它不需要使用很好的索引.
归档时间: |
|
查看次数: |
29847 次 |
最近记录: |