Do not miss any new update

How to Shorten a Name in java

Posted by aamir khan

How to Shorten a Name in java?



Without going in depth i would like to show you the Code...



/*----Program begin---*/
import java.util.Locale;
public class ShortName{
    public static void main(String[] args) {
        String name = "Aamir khan";
        String[] shortName = name.split("\\s");
        int len = shortName.length;
        switch(len){
            case 3: System.out.printf("%1.1s. %1.1s. %s", shortName[0].toUpperCase(Locale.ROOT),
                         shortName[1].toUpperCase(Locale.ROOT), shortName[2]);
                break;
            case 2: System.out.printf("%1.1s. %s", shortName[0].toUpperCase(Locale.ROOT),
                             shortName[1]);
                break;
            case 1: System.out.printf("%s", shortName[0]);
                break;
            default: System.out.println("Errorr !!! occured");
        }
        System.out.println("");
    }

}
/*---Program End---*/


updated one:

/*---Program Begin ---*/
    public static void main(String[] args) {
       
        String name = "Avul Pakir Jainulabdeen Abdul kalam";
        String[] splitedName = name.split("\\s");
        String shortName = "";
       
        int len = (splitedName.length - 1);

        for (int i = 0; i < len; i++)
            shortName = shortName.concat(splitedName[i].charAt(0) + ". ");
       
        shortName = shortName.concat(splitedName[len]);
        System.out.println(shortName.toUpperCase());
    }
/*---Program End---*/
Note : There may be other ways to do the same task, above code is just an idea and can be Optimize

{ 0 comments... read them below or add one }

Post a Comment

What you Says

..-

Related Posts Plugin for WordPress, Blogger...

If you like this blog,then link back to me.
This is what you will see.



Optionally use this Widget installer to add this link to your blogger blog.