I have a String "aabccdeef"
Now i want to capitalize only first occurrence of each char so that the o/p is AaBCcDEeF in Java
CodePudding user response:
I would do it this way (since I love java streams)
public static String capitalizeFirstOccurrence(String str) {
var alreadyOccurred = new HashSet<String>();
return str.chars()
.mapToObj(x -> String.valueOf((char) x)) // convert to single char String
.map(character -> {
if (alreadyOccurred.contains(character)) {
return character;
}
alreadyOccurred.add(character);
return character.toUpperCase();
})
.collect(Collectors.joining());
}
public static void main(String[] args) {
var input = "aabccdeef";
var output = capitalizeFirstOccurrence(input);
System.out.println(output);
}