Thursday 26 March 2020

Capitalize first letter of every word in string

StringUtil.java
package com.smaple.app.utils;

public class StringUtil {
    public static String capitalizeFirstCharOfEveryWord(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        StringBuilder builder = new StringBuilder();
        boolean spaceFound = true;

        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);

            if (ch == ' ') {
                builder.append(ch);
                spaceFound = true;
                continue;
            } else if (spaceFound) {
                builder.append(Character.toUpperCase(ch));
            } else {
                builder.append(ch);
            }

            spaceFound = false;
        }

        return builder.toString();
    }


}

StringUtilTest.java

package com.sample.app.utils;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.List;

import org.junit.Test;

import com.smaple.app.utils.StringUtil;

public class StringUtilTest {

    @Test
    public void emptyString() {
        String str = "";

        assertEquals(StringUtil.capitalizeFirstCharOfEveryWord(str), "");

    }

    @Test
    public void nullString() {
        String str = null;

        assertEquals(StringUtil.capitalizeFirstCharOfEveryWord(str), null);

    }

    @Test
    public void randomString() {
        String str1 = "Hello";
        String str2 = "hello";
        String str3 = "hello how    are you";
        String str4 = "a for apple, b for ball";
        String str5 = " a for apple, b for ball";

        String expected1 = "Hello";
        String expected2 = "Hello";
        String expected3 = "Hello How    Are You";
        String expected4 = "A For Apple, B For Ball";
        String expected5 = " A For Apple, B For Ball";
        
        assertEquals(expected1, StringUtil.capitalizeFirstCharOfEveryWord(str1));
        assertEquals(expected2, StringUtil.capitalizeFirstCharOfEveryWord(str2));
        assertEquals(expected3, StringUtil.capitalizeFirstCharOfEveryWord(str3));
        assertEquals(expected4, StringUtil.capitalizeFirstCharOfEveryWord(str4));
        assertEquals(expected5, StringUtil.capitalizeFirstCharOfEveryWord(str5));
    }
}




You may like

No comments:

Post a Comment