簡體   English   中英

如何在ArrayList中保存的字符串之間選擇文本

[英]How to select text between strings held in ArrayList

無法解決這個問題。 我正在使用apache POI從.doc中選擇粗體文本。 我已將此添加到數組列表。 我想從位於arrayList中連續字符串之間的.doc中選擇文本,然后分別存儲每個選定的部分。

換句話說,我有這個:

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);
           }

        }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM