0

I am given a String name say String s in below code. This String contains a phrase i.e. one or more words separated by single spaces. This program computes and return the acronym of this phrase.

import java.math.*;
import java.util.*;
import static java.util.Arrays.*;
import static java.lang.Math.*;
public class Initials {
  public String getInitials(String s) {

    String r = "";
    for(String t:s.split("\\s+")){
      r += t.charAt(0);
    }
    return r;
  }


  void p(Object... o) {
          System.out.println(deepToString(o));
      }


}

Example: "john fitzgerald kennedy"

Returns: "jfk"

Abhishek Sharma
  • 113
  • 1
  • 4
  • 11
  • 2
    What documentation tells you? http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) – talex Oct 17 '16 at 15:56
  • See this link will help you. http://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-any-whitespace-chars-as-delimiters – Ankit Shah Oct 17 '16 at 16:00
  • It means that someone didn't understand that String.split() without any parameters already means split on white space. – Bill K Mar 20 '18 at 15:52

2 Answers2

18

split("\\s+") will split the string into string of array with separator as space or multiple spaces. \s+ is a regular expression for one or more spaces.

Jordi Castilla
  • 26,609
  • 8
  • 70
  • 109
Manoj Mohan
  • 633
  • 5
  • 13
5

It simply means: slice the input string s on the given regular expression.

That regular expression simply says: "one or more whitespaces". (see here for an extensive descriptions what those patterns mean)

Thus: that call to split returns an array with "john", "fitzgerald", ... That array is directly "processed" using the for-each type of for loops.

When you then pick the first character of each of those strings, you end up with "jfk"

GhostCat
  • 137,827
  • 25
  • 176
  • 248