2013-05-07 107 views
-8

我百思不得其解,为什么posOfDot将返回15:为什么indexOf返回一个不正确的索引?

for(String l2 : list2){ 

    System.out.println("l2FileNAme: "+l2); 
    int posOfI= l2.indexOf("_")+1; 
    System.out.println("posOfI: "+posOfI); 

    String l2FileName = l2.substring(0,posOfI); 
    System.out.println("l2FileNAme: "+l2FileName); 

    for(String l1 : list1){ 

     int posOfDot= l2.indexOf("."); 
     System.out.println("posOfDot: "+posOfDot); 
     //substring the root of the file 
     //String l1FileName = l1.substring(0,posOfDot); //fails here as posOfDot exceeds string length in substring. 
     System.out.println("l1FileNAme: "+l1); 
    } 
} 

输出:

l2FileNAme: scenario8_items.txt 
posOfI: 10 
l2FileNAme: scenario8_ 
posOfDot: 15 
l1FileNAme: scenario8_.csv 

我期待posOfDot为10,就像posOfI,但它返回15.如何来?

我已经试过:

  • lastIndexOf
  • 的indexOf
  • 两个字符符号和字符串符号( '' 和 “”)

- 编辑 -

每个列表(列表1和列表2)都包含一个文件名列表。这些不是实际的文件本身,而只是文件名。

+2

我们应该如何知道这些文件中有什么? – m3th0dman 2013-05-07 20:16:03

+0

我没有搜索文件 - 我正在搜索文件名。 – 2013-05-07 20:16:50

+5

也许使用正确的'String'会产生更好的结果?最好举例说明为什么不给这样的变量命名,即使你认为没有什么可能出错。 'int posOfDot = l2.indexOf(“。”);' - 这就是*完全*其中'.'在'l2'中 – 2013-05-07 20:17:53

回答

4
l2FileNAme: scenario8_items.txt 

计数屏幕上的字,.是在第16位,这是15一个从零开始的索引。你在l2上执行此操作。

似乎正确的输出给我。

相关问题