如何在ArrayList中的字符串之间选择文本



无法解决这个问题。我使用apachePOI从.doc中选择粗体文本。我已经将其添加到数组列表中。我想从.doc中选择位于arrayList中连续字符串之间的文本,然后分别存储每个选定的部分。

换句话说,我有这个:

MyBold title
Bla
bla
fsfs
bn
whtrh
More bold title
gfgdgdfs
dsgfd
gfdg
Another title of some kind

得到的arrayList给了我这个:

MyBold title
More bold title
Another title of some kind

我想把它作为单独的字符串对象第一个对象:

MyBold title
    Bla
    bla
    fsfs
    bn
    whtrh

第二个对象:

More bold title
    gfgdgdfs
    dsgfd
    gfdg

第三个对象:

Another title of some kind

到目前为止我的代码:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.wp.usermodel.CharacterRun;
public class Impedance {
    String REGEX = "[A-Z]+";
    public Impedance()  {
    }
        // TODO Auto-generated constructor stub
         public static void Update() throws IOException {
    try{
    String fileName = "/Users/IMPEDANCE.doc";
    InputStream fis = new FileInputStream(fileName);  
    POIFSFileSystem fs = new POIFSFileSystem(fis);  
    HWPFDocument doc = new HWPFDocument(fs);  
    Range range = doc.getRange();
    WordExtractor we = new WordExtractor(doc);
    Paragraph r =range.getParagraph(0);
    ArrayList<String> bold1 = new ArrayList<String>();
    for(int i = 0; i<range.numCharacterRuns(); i++)
    {

            CharacterRun cr = range.getCharacterRun(i);
            if(cr.isBold())
            {
            System.out.println(cr.text());
            bold1.add(cr.text());
            }
    }

    for (String bold : bold1) {
    //How to iterate through array list and return the string section between consecutive parts of the arraylist
    }
 }
}

您可以使用Map,其中键是标题,值是字符串列表。

Map<String, List<String>> map  = new Hashmap<>();
String currentTitle = null;
for(int i = 0; i<range.numCharacterRuns(); i++){
    CharacterRun cr = range.getCharacterRun(i);
    //if the cr is bold, add it as a title
    if(cr.isBold()){
        currentTitle = cr.text();
        map.put(currentTitle, new ArrayList<String>());
        }else{
            //if the cr is not bold, get the last inserted title and
            //add the cr to its String list
            List<String> list = map.get(currentTitle);
            if(list != null){
                list.add(cr.text());
                map.put(currentTitle, list);
           }
        }
}

相关内容

  • 没有找到相关文章

最新更新