s.split("\\ s +"))在下面的代码中的含义是什么?

Abh*_*rma -5 java arrays string for-loop

我在下面的代码中给出了一个字符串名称字符串.此字符串包含一个短语,即由单个空格分隔的一个或多个单词.该程序计算并返回此短语的首字母缩写词.

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));
      }


}
Run Code Online (Sandbox Code Playgroud)

示例:"john fitzgerald kennedy"

返回:"jfk"

小智 7

split("\\s+")将字符串拆分为数组字符串,其中分隔符为空格或多个空格.\s+是一个或多个空格的正则表达式.


Gho*_*ica 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.

然后,当您选择每个字符串的第一个字符时,您最终会得到“jfk”