Skip to content

Instantly share code, notes, and snippets.

@jurigis
Last active April 29, 2016 18:28
Show Gist options
  • Save jurigis/18eae225dbfbcfe71b0f72198211c864 to your computer and use it in GitHub Desktop.
Save jurigis/18eae225dbfbcfe71b0f72198211c864 to your computer and use it in GitHub Desktop.
Adding hash tag charactor to a string (adding #)
import java.util.List;
/**
* Adds the # character to all words of the text.
*
* @author https://github.com/jurigis
*/
public class HashTagBuilder {
public static String addHashTags(final String textToTag, final List<String> wordList) {
// If the list of words is empty we return the text as it is.
if (wordList == null || wordList.isEmpty()) {
return textToTag;
}
final StringBuilder sb = new StringBuilder(textToTag);
wordList.stream().filter(word -> (word != null && !word.isEmpty())).forEach(word -> {
int currentPos = 0;
while (currentPos >= 0) {
currentPos = sb.toString().toLowerCase().indexOf(word.toLowerCase(), currentPos);
if (currentPos > 0) {
sb.insert(currentPos, '#');
currentPos += 2;
}
}
});
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment