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"
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”