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

Time:05-29

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.

CodePudding user response:

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