java s.split("\\s+")) 在下面的代码中是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40090776/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does s.split("\\s+")) means here in the below code?
提问by Abhishek Sharma
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.
我在下面的代码中得到了一个 String 名称,比如 String s。该字符串包含一个短语,即一个或多个由单个空格分隔的单词。该程序计算并返回该短语的首字母缩写词。
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"
返回:“jfk”
回答by Manoj Mohan
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.
split("\\s+")
将字符串拆分为数组字符串,分隔符为空格或多个空格。\s+
是一个或多个空格的正则表达式。
回答by GhostCat
It simply means: slice the input string son the given regular expression.
它只是意味着:在给定的正则表达式上对输入字符串s进行切片。
That regular expression simply says: "one or more whitespaces". (see herefor 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.
因此:对 split 的调用返回一个带有“john”、“fitzgerald”、...的数组,该数组使用 for-each 类型的 for 循环直接“处理”。
When you then pick the first character of each of those strings, you end up with "jfk"
当您选择每个字符串的第一个字符时,您最终会得到“jfk”