-1

i want to print first character from multiple word , this word coming from api , like DisplayName: arwa othman . i want to print the letter (a) and (o). can anyone to help me please ??

matiash
  • 54,791
  • 16
  • 125
  • 154

3 Answers3

3

Try this

   public String getFirstWords(String original){
       String firstWord= "";
       String[] split = original.split(" ");

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

        return firstWord;
    }

And use this as

String Result = getFirstWords("arwa othman");

Edit Using Regex

String name = "arwa othman";
String firstWord= "";
for(String s : name.split("\\s+")){
 firstWord += s.charAt(0);
}

String Result = firstWord;
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
0

You can use the the Apache Commons Langs library and use the initials() method , you can get more information from here http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html#initials(java.lang.String)

I am quoting a sample code snippet that might be useful :

WordUtils.initials(null)             = null
WordUtils.initials("")               = ""
WordUtils.initials("Ben John Lee")   = "BJL"
WordUtils.initials("Ben J.Lee")      = "BJ"
Shubhang Malviya
  • 1,525
  • 11
  • 17
0

This may work for you:

String[] splitArray = displayName.split("\\s+");
char[] initials = new char[splitArray.length];
for (int i = 0; i < splitArray.length; i++) {
    initials[i] = splitArray[i].charAt(0);
}

This will give you a char array. If you want a String array use String.valueOf(char)

Fletcher Johns
  • 1,236
  • 15
  • 20