简体   繁体   English

在Java / Android中多次复制字符串的一部分

[英]Copying parts of a string several times in Java/Android

I have a source code from a website where textmessages start with "< h2 >" and end with "< /h2 >". 我有一个网站的源代码,其中文本消息以“ <h2>”开头,以“ </ h2>”结尾。 In my app, I read the source code and make it into a string. 在我的应用程序中,我阅读了源代码并将其制成字符串。 Now I want to read only the messages, and have tried with this: 现在,我只想阅读消息,并对此进行了尝试:

returned = get.getInternetData("http://blablabla.com");
int start = returned.indexOf("<h2>") + 4;
int end = returned.indexOf("</h2>");
String message = returned.substring(start, end);

The problem is that I only get the very first message! 问题是我只收到第一条消息! My idea was to use a scanner object and do something like 我的想法是使用扫描仪对象并执行类似的操作

while (scan.hasNext("<h2>")) {
        }

But there are no get-methods from the scanner. 但是,扫描仪没有任何获取方法。 How can read all the messages from the source code? 如何从源代码中读取所有消息?

you should do something like this: 您应该执行以下操作:

while (returned.indexOf("<h2>", lastIndex)!=-1) {
   .... 
   do your thing
   ...
   increment lastIndex 
}

Using Jsoup you can do this: 使用Jsoup,您可以执行以下操作:

 Document doc = Jsoup.connect("http://blablabla.com").get();
 Elements h2Tag = doc.select("h2");
 ArrayList<String> messages = new ArrayList<String>();
 for(Element mess: h2Tag){
     messages.add(mess.text());
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM