2014-01-07 27 views
0

這是一種在某些文本中基本上擺脫html標記的方法。方法刪除由以下給出,我測試它,它的工作原理。在方法中提取循環外部的變量

public static String remove(String text, String str) { 

    int firstIndex = text.indexOf(str); 
    int beginofNewIndex = (firstIndex + 1) + str.length(); 

    if (firstIndex > 0) { 
     return text.substring(0, firstIndex) + text.substring(beginofNewIndex); 
    } else { 
     return text; 
    } 
} 

但是,當我返回下面給出的「文本」時,它給了我與輸入時相同的值。假設方法removeAllTags的參數是String文本。我輸入「< b>這個男孩走了</b>」但它返回相同的東西。有沒有人看到任何錯誤?

public static String removeAllTags(String text) { 

    int textLength = text.length(); 

    while (textLength > 2) { 
     int firstIndex = text.indexOf("<"); 
     int secondIndex = text.indexOf(">"); 
     int thirdIndex = text.indexOf("</", secondIndex); 
     int fourthIndex = text.indexOf(">", secondIndex); 

     if (firstIndex >= 0 && secondIndex >= 0 && thirdIndex >= 0 && fourthIndex >= 0F) { 


      remove(text, text.substring(firstIndex, (secondIndex + 1))); 
      // remove(text, text.substring(thirdIndex, (fourthIndex + 1))); I will implement this into the code but I am testing with the first remove method first. 



     } 
     textLength = textLength - 1; 
    } 
    return text; 

} 
+0

你必須這樣做嗎?也許看到這個問題:http://stackoverflow.com/questions/832620/stripping-html-tags-in-java – Catchwa

回答

1

的問題是你的字符串和條件

"< b> The boy walked </b>" 

這串你有空間<之間空間/b>中,這給了

int thirdIndex = text.indexOf("</", secondIndex); 

假的結果,這就是爲什麼它不會進入循環,並且您需要使用返回的文本分配文本

text = remove(text, text.substring(firstIndex, (secondIndex + 1))); 

您還可以使用正則表達式來刪除所有HTML標記

str.replaceAll("\\<.*?>","") 
+0

嗯,我之間的空間主要是因爲如果我不然,那麼stackoverflow會自動將它轉換成粗體字但thx – Freedom

+0

@LyalyalKnight你不能使用正則表達式呢? –

+0

你是什麼意思? – Freedom

2

的關鍵問題是這一行:

remove(text, text.substring(firstIndex, (secondIndex + 1))); 

這什麼都不做。

Java不會像C一樣通過引用傳遞,並且字符串是不可變的,所以對傳入的字符串所做的任何更改都不會反映在方法外部。

相反,你必須分配結果返回給變量:

text = remove(text, text.substring(firstIndex, (secondIndex + 1))); 

不管其他問題有可能是你的代碼,這個是最大的。

+0

我試着用text = remove(text,text.substring(firstIndex,(secondIndex) + 1)));但我得到一個錯誤,當我運行它:異常在線程「主」java.lang.StringIndexOutOfBoundsException:字符串索引超出範圍:-13 \t在java.lang.String.substring(String.java:1911) \t at htmlprocessor.HTMLProcessor.removeAllTags(HTMLProcessor.java:83) \t at htmlprocessor.HTMLProcessor.main(HTMLProcessor.java:32) Java結果:1爲什麼會這樣? – Freedom

1
try this give your comment 
change these lines 
int beginofNewIndex = (firstIndex) + str.length(); 
this will point new char after > 
and 
if (firstIndex >= 0) 
this will accept when < is in first index like <br>hai.