2013-02-20 2 views
7

Jsoup를 사용하여 웹 사이트에서 HTML을 구문 분석하여 ArrayList을 웹 사이트에서 가져와야하는 사이트로 채 웁니다. 이제 문자열이 채워진 ArrayList이 생겼습니다. 해당 문자열에서 특정 문자열을 포함하는 색인을 찾고 싶습니다. 예를 들어, 목록의 어딘가에 어떤 인덱스에서 문자열 (리터럴) "Claude"가 있지만 의 contains "Claude"인덱스를 찾는 코드를 만들 수없는 것으로 나타났습니다. 여기에 내가 시도 것입니다 만 (찾을 수 없음) -1를 반환 : 당신은 String.indexOfList.indexOf을 혼동하고문자열이 포함 된 ArrayList에서 인덱스 찾기

ArrayList <String> list = new ArrayList <String>(); 
String claude = "Claude"; 

Document doc = null; 
try { 
    doc = Jsoup.connect("http://espn.go.com/nhl/team/stats/_/name/phi/philadelphia-flyers").get(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
for (Element table: doc.select("table.tablehead")) { 
    for (Element row: table.select("tr")) { 
     Elements tds = row.select("td"); 
     if (tds.size() > 6) { 
      String a = tds.get(0).text() + tds.get(1).text() + tds.get(2).text() + tds.get(3).text() + tds.get(4).text() + tds.get(5).text() + tds.get(6).text(); 

      list.add(a); 

      int claudesPos = list.indexOf(claude); 
      System.out.println(claudesPos); 
     } 
    } 
} 
+3

가되어'Claude' 더 큰 문자열, 또는 자신의 목록에있는 문자열의 일부? –

+0

문자열'a'를 인쇄하고 "Claude"를 확인하십시오. 거기에 있어서는 안된다. JSoup를 사용하여 html 태그를 반복하는 방법에 대한 작업 – LGAP

+0

"Claude"가 목록에 추가되면 -1을 얻는 이유가 표시되지 않습니다. 삽입하는 동안 여분의 공간에 대한 경계, 삽입하기 전에 트림을 사용할 수 있습니다. 케이스도 중요한데, "클로드"는 "클로드"와 다릅니다. – sudmong

답변

25

. 그래서

list[0] = "Alpha Bravo Charlie" 
list[1] = "Delta Echo Foxtrot" 
list[2] = "Golf Hotel India" 

list.indexOf("Foxtrot") => -1 
list.indexOf("Golf Hotel India") => 2 
list.get(1).indexOf("Foxtrot") => 11 

: 다음 목록을 고려

if (tds.size() > 6) { 
    // now the string a contains the text of all of the table cells joined together 
    String a = tds.get(0).text() + tds.get(1).text() + tds.get(2).text() + 
     tds.get(3).text() + tds.get(4).text() + tds.get(5).text() + tds.get(6).text(); 

    // now the list contains the string 
    list.add(a); 

    // now you're looking in the list (which has all the table cells' items) 
    // for just the string "Claude", which doesn't exist 
    int claudesPos = list.indexOf(claude); 
    System.out.println(claudesPos); 

    // but this might give you the position of "Claude" within the string you built 
    System.out.println(a.indexOf(claude)); 
} 

for (int i = 0; i < list.size(); i += 1) { 
    if (list.get(i).indexOf(claude) != -1) { 
    // list.get(i).contains(claude) works too 
    // and this will give you the index of the string containing Claude 
    // (but not the position within that string) 
    System.out.println(i); 
    } 
} 
0
First check whether it is an instance of String then get index 

if (x instanceof String) { 
    ... 
} 

for (int i = 0; i < list.size(); i++) { 
    if (list.get(i).getX() == someValue) { // Or use equals() if it actually returns an Object. 
     // Found at index i. Break or return if necessary. 
    } 
} 
관련 문제