Steerpike
Steerpike

Reputation: 1833

Capitalizing first char in every word in a String in java (but ignoring specific word)

Can anyone please tell me why the following code prints 1 the high street and not 1 The High Street?:

    String propertyPageTitle = "1-the-high-street";
    propertyPageTitle = propertyPageTitle.replace("-", " ");
    WordUtils.capitalizeFully(propertyPageTitle);
    System.out.println(propertyPageTitle);

EDIT to show solution:

    String propertyPageTitle = "1-the-high-street";
    propertyPageTitle = propertyPageTitle.replace("-", " ");
    propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);
    System.out.println(propertyPageTitle);

Supposing I wanted to ignore the word 'and' if it appears (I'm reading values from a .csv) and NOT change to titlecase? how would that be possible.

Upvotes: 0

Views: 374

Answers (4)

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

    String toBeCapped = "1 the high street and 2 low street";

    String[] tokens = toBeCapped.split("\\s");
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < tokens.length; i++) {
        if (!tokens[i].equalsIgnoreCase("and")) {
            char capLetter = Character.toUpperCase(tokens[i].charAt(0));
            builder.append(" ");
            builder.append(capLetter);
            builder.append(tokens[i].substring(1, tokens[i].length()));
        } else {
            builder.append(" and");
        }
    }
    toBeCapped = builder.toString().trim();
    System.out.println(toBeCapped);

output:

1 The High Street and 2 Low Street

Upvotes: 0

AJJ
AJJ

Reputation: 3628

String firstStr = "i am fine";
String capitalizedStr = WordUtils.capitalizeFully(firstStr);
System.out.println(capitalizedStr);

The return should be taken to get the output of a method. It is common for all methods in Java String

Upvotes: 0

Aman Agnihotri
Aman Agnihotri

Reputation: 3023

This happens because capitalizeFully(String) of WordUtils returns a String which has the expected answer. So try:

propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);

And then it will work.

Upvotes: 1

Joachim Isaksson
Joachim Isaksson

Reputation: 180867

WordUtils.capitalizeFully does not change the original String, but instead returns the capitalized String.

propertyPageTitle = WordUtils.capitalizeFully(propertyPageTitle);

Upvotes: 1

Related Questions