简体   繁体   中英

How to find words in a string from given list of keywords in java

Suppose I have a String like this.

String s = "I have this simple string java, I want to find keywords in this string";

Meantime I have a list of Keywords like this.

ArrayList<String> keywords = new ArrayList<>( Arrays.asList("string", "keywords"));

What I want to achieve is find out words in the s from keywords and generate a new string with highlighted keywords.like

String sNew = "I have this simple string java, I want to find keywords in this string ";

This highlighting part is done through iText while generating a pdf.

Thanks.

Based from https://stackoverflow.com/a/27081059/7212686 , add Chunk with custom font

public static final Font BLACK_NORMAL = new Font(FontFamily.HELVETICA, 12, Font.NORMAL);
public static final Font BLACK_BOLD = new Font(FontFamily.HELVETICA, 12, Font.BOLD);

String s = "I have this simple string java, I want to find keywords in this string";
List<String> keywords = Arrays.asList("string", "keywords");

Paragraph p = new Paragraph();
for (String word : s.split("\\s+")) {
    if (keywords.contains(word))
        p.add(new Chunk(word, BLACK_BOLD));
    else
        p.add(new Chunk(word, BLACK_NORMAL));
    
    p.add(new Chunk(" ", BLACK_NORMAL));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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