I’m trying to write a method that will scan a string for certain characters, and report back which of them (if any) were found:
// Special characters are ~, #, @, and *
// If text == "Hello~Clarice, you're s#o ambitious", then this
// method should return a string == "~#". If no special characters
// found, return null. If the same special character occurs 2+ times,
// ignore it and do not return strings with duplicate special chars, like
// "##@***", etc. --> just "#@*".
public String detectAndGetSpecialCharacters(String text) {
Pattern p = Pattern.compile("[~#@*]");
Matcher m = pattern.matcher(text);
String specialCharactersFound = null;
if(m.find()) {
// ???
}
return specialCharactersFound;
}
I’ve completed the detect portion of this method, but am struggling to find an efficient/elegant way of using the Matcher to tell me which special characters were found, and furthermore, to concatenate them all together (removing duplicates!) and return them. Thanks in advance!
Rather than using a String, you can use a
StringBuilder, and append each matched character to it, if it is not already there: –Another way would be to maintain a
Set<String>, and keep on adding matched characters to it. It will automatically remove duplicates. And then you can merge the values of theSetto form aStringusing Apache CommonsStringUtils#join()method. Or you can simply iterate over theSetand append each string to aStringBuilderobject. Whatever way you like would fit.