[英]Cannot get the correct substrings from this string
我只想最后獲得“ @”和“,”(或“]”)之間的數字和字母; 然后將它們添加到arraylist。 為什么這不起作用? 沒想停在逗號...
ArrayList<String> listUsers=new ArrayList<String>();
String userToAdd = new String();
String objectInText;
objectInText="[jkasdas@8677bsd,hjkhj@554asd3]";
for (int i=0;i<objectInText.length();i++){
if (objectInText.charAt(i)=='@'){
int j=i;
while((objectInText.charAt(j)!=',') || (objectInText.charAt(j)!=']') ){
userToAdd+=objectInText.charAt(j+1);
j++;
}
listUsers.add(userToAdd);
System.out.println(userToAdd);
userToAdd="";
}
}
while((objectInText.charAt(j)!=',') || (objectInText.charAt(j)!=']'))
您正在循環,直到當前字符不是','或不是']'
這基本上意味着循環僅在char同時為','和']'時才停止,這顯然是不可能的。
您應該替換“ ||” 與“ &&”一起使用,這樣只要j既不是','也不是']',while循環就會繼續。
注意
我不知道這是否對您有幫助,但是如果您知道在'@'和'之間,則只有字母和數字(沒有特殊字符,因為您說的是字母和數字),並且您也知道“ @”和“,”僅出現1次,您也可以執行以下操作:
int startIndex = objectInText.indexOf('@')+1;
int endIndex = objectInText.indexOf(',');
String userToAdd =objectInText.substring(startIndex, endIndex);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.