I have been using apache WordUtils to capitalize every first letter in a String, but I need only the first letter of certain words to be capitalized and not all of them. Here is what I have:
import org.apache.commons.lang.WordUtils;
public class FirstCapitalLetter {
public static void main(String[] args) {
String str = "STATEMENT OF ACCOUNT FOR THE PERIOD OF";
str = WordUtils.capitalizeFully(str);
System.out.println(str);
}
}
My Output is:
Statement Of Account For The Period Of
I want my output to be
Statement of Account for the Period of
How can I achieve this?
1) Create a set of String you do not want to capitalize (a set of exceptions):
Set<String> doNotCapitalize = new HashSet<>();
doNotCapitalize.add("the");
doNotCapitalize.add("of");
doNotCapitalize.add("for");
...
2) Split the string by spaces
String[] words = "STATEMENT OF ACCOUNT FOR THE PERIOD OF".split(" ");
3) Iterate through the array, capitalizing only those words that are not in the set of exceptions:
StringBuilder builder = new StringBuilder();
for(String word : words){
String lower = word.toLowerCase();
if(doNotCapitalize.contains(lower){
builder.append(lower).append(" ");
}
else{
builder.append(WordUtils.capitalizeFully(lower)).append(" ");
}
}
String finalString = builder.toString();
仅当字符串的长度大于3时,才对字符串中的每个单词运行WordUtils.capitalizeFully,这在此特定情况下有效
U need to break the string in three parts
1. Statement of
2. Account for the
3. Period of.
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.