如果我有一个String数组,如下所示。
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
我想将所有内容从“H ----”复制到“----”。那应该是“SinghSawhRaman”(不包括“H ----”和“----”。
这样的事情:
String keywords = "";
int j = 0;
for(int i = 0; i < name.length; i++){
if(name[i].contains("H ---- ")){
for(j = i; j < 5; j++){
// There problem is j < 5. I want to give a condition when name[i].contains(" ---- ")
// but not sure how should I be able to do it.
keywords = keywords + name[j];
}
有人可以告诉我最好的方法吗?
答案 0 :(得分:3)
for(j = i; !name[j].contains(" ---- "); j++){
keywords = keywords + name[j];
}
这应该对你有用,你可以将for
循环的中断条件设置为任何布尔表达式。
编辑:当条件为假时,需要!
作为循环中断。
答案 1 :(得分:0)
您使用contains
代替equals
?
如果使用equals
也适合您,可以使用List
:
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
List<String> s = Arrays.asList(name);
StringBuilder sb = new StringBuilder();
for(int i = s.indexOf("H ---- ")+1; i < s.indexOf(" ---- "); i++)
sb.append(s.get(i));
System.out.println(sb);
答案 2 :(得分:0)
我会这样做
private static String copyFrom(String[] in, String begin, String end) {
StringBuilder sb = new StringBuilder();
boolean start = false;
if (in != null) {
for (String s : in) {
if (!start) {
start = s.equals(begin);
} else {
start = !s.equals(end);
if (start) {
sb.append(s);
}
}
}
}
return sb.toString();
}
public static void main(String[] args) {
String[] name = {"aval", "H ---- ", "Singh", "Sawh",
"Raman", " ---- ", "parminder", "kaur",
"jaspreet", "asneet", " ---- "};
String keywords = copyFrom(name, "H ---- ", " ---- ");
System.out.println(keywords);
}
输出
SinghSawhRaman
答案 3 :(得分:0)
String keywords = "";
boolean append = false;
for(j = 0; j <= name.length; j++) {
if(name[j].contains("H----")
append = true;
if(append)
keywords += name[j];
if(name[j].contains("----") {
append = false;
break;
}
}
请注意,如果您移动if(name[j].contains("H----")
块下方的if(append)
块,则会从H---
字符串中排除keywords
;
答案 4 :(得分:0)
一旦达到条件,只需突破外部循环:
boolean capture = false;
for (String n : name) {
if (n.contains("H ---- ")) {
capture = true;
} else if (n.contains(" ---- ")) {
break;
} else if (capture) {
keywords = keywords + n;
}
}
如果多次出现H ----
和----
,则不要break
退出循环,只需设置capture = false
而不是break
使用两个嵌套循环,您将读取构成名称一部分的任何元素两次,这是低效的。除非可以使用嵌套 H ----
创建名称,否则最好删除内部循环。
答案 5 :(得分:0)
String[] name = {"aval", "H ---- ", "Singh", "Sawh", "Raman", " ---- ", "parminder", "kaur", "jaspreet", "asneet", " ---- "};
String key ="";
boolean flag = false;
for(String s : name){
if(s.equals("H ---- ")){
flag = true;
}
if(s.equals(" ---- ")){
flag = false;
}
if(flag && !s.equals("H ---- ")){
key+=s;
}
}
System.out.println(key);