2015-05-20 90 views
-3

我有一個HTML字符串:<myTag>寶貝</myTag >。
我想在Java中使用文本「Baby」。這裏要注意的是,標籤可以是小寫或大寫,例如:<MYTAG>寶貝</MyTag >。
有人可以幫我嗎?從HTML字符串中提取文本時出現問題

+3

請與我們分享您的代碼,以便我們可以幫助你改進/修復它 – User404

+2

你可以分享的任何代碼? –

+1

作爲一個黑客,你可以嘗試'String result = str.substring(str.indexOf(「>」)+ 1,str.indexOf(「<」));'或者簡單的大寫字符串來獲取開始和結束點 –

回答

0

試試這個代碼:

public class Test { 

    public static void main(String[] args) { 

     String html = "<MYTAG>Baby</MyTag>"; 
     String content = ""; 

     boolean read = true; 

     for(char c : html.toCharArray()) { 

      if(c == '<' || c == '/') { 
       read = false; 
      } 

      if(c == '>') { 
       read = true; 
      } 

      if(read) { 

       if(c != '>') 
        content += c; 
      } 
     } 

     System.out.println(content); 
    } 

} 

輸出:嬰兒

+0

感謝shekhar suman和Soumitri。您的解決方案能夠運作但可能會出現以下情況:名稱寶貝。我只能刪除。 –

+0

@AbhishekKumar它它幫助你,然後請將它投票並標記爲答案,謝謝:) –

2

你可以使用下面的代碼: -

String given = "<MYTAG>Baby</MyTag>"; 
String required = given.substring(given.indexOf('>')+1,given.lastIndexOf('<'); 
+0

@ AbhishekKumar - 爲此,你只需要執行 - > '字符串required = given.substring(given.indexOf(「 「)+ 1,given.indexOf(」「);' –