-1

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?

Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
Stanley Mungai
  • 4,044
  • 30
  • 100
  • 168
  • This is for all leters and I ca already do that As I have already stated. – Stanley Mungai Dec 13 '12 at 07:52
  • I doubt that you can do this with WordUtils. You will have to write your own method and maintain a list of words that you don't want them capitalized. – Adrian Ber Dec 13 '12 at 07:56
  • I don't think there's any ready made utility; however if you are sure that this is always going to be the pattern, you could just use capitalize and then replace (account) with (Account) and (period) with (Period) by the use of a replace function. – Scorpion Dec 13 '12 at 07:57
  • Out of curiosity: why do you want to capitalize "Account" and "Period"? And out of technical necessity: how do you plan to detect the kind of words that need capitalization? Do you have a list of those? – Joachim Sauer Dec 13 '12 at 08:01
  • 1
    I think you want to capitalize the string except preposition – Mohammod Hossain Dec 13 '12 at 08:03
  • Mohammod Right.... I wonder why some people are so quick to down vote Questions without a reason. – Stanley Mungai Dec 13 '12 at 08:04

3 Answers3

2

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();
Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
1

Run WordUtils.capitalizeFully for each word in your string only if its length is longer than 3, this will work in this specific case

CloudyMarble
  • 36,908
  • 70
  • 97
  • 130
0

U need to break the string in three parts
1. Statement of
2. Account for the
3. Period of.