2013-02-20 17 views
7

Jsoupを使用して、WebサイトからHTMLを解析して、ArrayListにウェブサイトから取得する必要があるものを設定します。だから私は文字列でいっぱいのArrayListを持っています。私は特定の文字列を含むそのリスト内のインデックスを探したい。たとえば、リストのどこかにあるインデックスで、文字列(リテラル) "Claude"があることがわかりますが、のcontains "Claude"というインデックスを見つけるコードを作成できません。文字列を含む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を得る理由はありません。挿入中に余分なスペースを探して、挿入する前にトリムを使用することがあります。また、 "Claude"は "claude"とは異なります。 – sudmong

答えて

25

あなたがString.indexOfList.indexOfを混乱している:ここで私は(見つからない)しようとしたが、-1を返してきたものです。以下のリストを考える:

だから、
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. 
    } 
} 
関連する問題