2010-03-31 68 views
2

這一定很簡單,但我很困難。您看到我正在嘗試在另一個字符串中查找字符串,如下所示。爲什麼Java String indexOf失敗?

  e = input.indexOf("-->"); 
      s = input.indexOf("<!--"); 
      input = input.replace(input.substring(s, e + 3), " "); 

的整數e和s的返回-1,因爲它沒有被發現,這是導致替代方法失敗。我正在使用的測試字符串是"Chartered Certified<!--lol--> Accountants (ACCA)"。我試圖創造一個新的字符串對象,並在字符串中作爲參數傳遞如下

e=input.indexOf(new String("<!--")); 

這產生相同的結果。 任何想法?

這是一段獨立的代碼,我寫的很完美。

public static void main(String[] args) { 
    int e = 0; 
    int s = 0; 
    while (e != -1) { 
     //input.replace("\"", "\'"); 
     e = input.indexOf("-->"); 
     s = input.indexOf("<!--"); 
     input = input.replace(input.substring(s, e + 3), " "); 
     e = input.indexOf("-->"); 
     System.out.println(input); 
    } 
} 

但我似乎無法看到爲什麼它失敗時,我在我的操作類中使用此邏輯。

+1

沒有匹配你正在尋找的字符串。評論是否在格式化您的帖子時被解析出來? – 2010-03-31 17:41:00

+0

嘗試檢查您的輸入字符串 – Roman 2010-03-31 17:44:49

+2

您可以顯示代碼設置輸入值的位置嗎? – 2010-03-31 17:47:10

回答

1

字符串「特許公認會計師(ACCA)」不包含「 - >」或「<!」,因此es將始終爲-1。

+3

實際上,他發佈的字符串確實有它們,但它們被解釋爲HTML註釋並未顯示。我添加了一個代碼塊來顯示它們。 – 2010-03-31 17:40:56

+0

基本上我試圖手動去掉在java中這兩個註釋之間的任何字符。 befoer甚至擊中了jsp。所以它嚴格的java邏輯。 indexOf()方法返回-1,因爲該字符串沒有被java看到,但它是字符串的一部分。 – Binaryrespawn 2010-03-31 17:45:14

+0

請儘量聰明。這是一個評論HTML。它已經被降價.. – Jack 2010-03-31 17:45:30

3
System.out.println("!Chartered Certified<!--lol--> Accountants (ACCA)".indexOf("-->")); 

打印27

所以你輸入的字符串必須不是你所期望什麼

3
String input = "Chartered Certified<!--lol--> Accountants (ACCA)"; 
int e = input.indexOf("-->"); 
int s = input.indexOf("<!--"); 

System.out.println(e+" "+s); 

產生

所以我認爲其他地方有錯誤,中間是否有其他代碼?

+2

我對這個'<'的分實際上是一個'<'等等。 – BalusC 2010-03-31 17:48:40

+0

@Binaryrespawn請參閱上面的註釋 – Pyrolistical 2010-03-31 17:58:13

0

也許你是從一種XML解析器中獲取字符串,並在渲染時隱藏了註釋字符串。檢查indexOf調用之前的輸入字符串是否真的有'<!--''-->'字符串。

0

我使用命令行參數快速運行測試。它工作得很好。下面的代碼/結果:

public static void main(String[] args) { 
    String input = args[0]; 
    System.out.println(input); 
    int e = input.indexOf("-->"); 
    int s = input.indexOf("<!--"); 
    input = input.replace(input.substring(s, e + 3), ""); 
    System.out.println(input); 
} 

輸出:

Chartered Certified<!--lol--> Accountants (ACCA) 
Chartered Certified Accountants (ACCA) 

如果你路過input作爲命令行參數,確保它是在引號,否則input將被設置爲Chartered因爲的空間。

0

此代碼應該工作,還有一些其他問題。儘管如下所示,您應該對其進行編碼以確保安全。

e = input.indexOf("-->"); 
s = input.indexOf("<!--"); 
if (e > -1 && s > -1 && e > s + 4) { 
    input = input.replace(input.substring(s, e + "-->".length()), " "); 
} 
0

您的代碼似乎沒問題。所以如果失敗了。它可能是它解析的字符串不是你想象的那樣。字符串從哪裏來?在解析它之前嘗試打印字符串以查看它實際是什麼。