gpt4 book ai didi

java - 修剪字符串并添加到 ArrayList

转载 作者:行者123 更新时间:2023-12-01 10:06:21 25 4
gpt4 key购买 nike

变量 TEST 等于这个

lazar108@hotmail.com_Hd_s lazar108@hotmail.com_Update_on the lazar108@hotmail.com_Ksks_ajsj 

我想取出每个“产品”,这样我就有一个等于这个的ArrayList

lazar108@hotmail.com_Hd_s
lazar108@hotmail.com_Update_on
lazar108@hotmail.com_Ksks_ajsj

现在我的数组列表中唯一的东西是lazar108@hotmail.com_Hd_s

How can i pull each "product" from the one variable (TEST) in a loop and add it to the ArrayList?

到目前为止我的代码:

String TEST = result;

ArrayList<String> Products = new ArrayList<>();
boolean flag = true;

while(flag == true){
Products.add(TEST.substring(0, TEST.indexOf(' ')));
TEST = TEST.substring(TEST.indexOf(' ') + 1);

if(TEST.equals("")){
flag = false;
}else{
TEST = TEST.substring(1);
}
}

see

最佳答案

您距离实现这一目标仅一步之遥。在 while 循环的第一次迭代之后,您确实检索了 lazar108@hotmail.com_Hd_s,但此后循环无限运行,因为字符串的其他部分没有被访问。解决方案是每次将字符串添加到 Products 时,剪掉从字符串中检索到的部分。我还应该注意,只有当 TEST 以空格“”结尾时,这才有效。这是一种解决这个问题的方法。

String TEST = result;

ArrayList<String> Products = new ArrayList<>();
boolean flag = true;

while(flag == true){
Products.add(TEST.substring(0,TEST.indexOf(' ')));
TEST = TEST.substring(TEST.indexOf(' '));//cutting the last email added from the string
if(TEST.equals(" ")){
flag = false;
}
else{
TEST = TEST.substring(1); //remove that space so that it doesn't get
//counted again in the next iteration
}

}

关于java - 修剪字符串并添加到 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36439291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com