Getting the first letter of every word in a String using Java

This is a sample code on getting the first letter of every word in a String using Java. This may be helpful if you want to get the middle initial out of a middle name. If you have a middlename String with “de la Hoya” value and you want to have “dlH” then you use the code below

public class Test {
   public static String generateInitials ( String original ){
       String initial = "";
       String[] split = original.split(" ");

       for(String value : split){
            initial += value.substring(0,1);
        }

        return initial;
    }

    public static void main(String[] arg){
        System.out.println( generateInitials("de la Hoya") );
    }
}

Compiling and runnning the code will output dlH in your command line

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s