java.lang.String
我应该使用哪种方法将下面的字符串拆分为字符串数组或字符串集合,该拆分是针对换行符进行的?
String str="This is a string\nthis is the next line.\nHello World.";
我认为那是split()
。
String[] arrOfStr = str.split("\n", limit)
;
但我不知道limit
为了遵循要求要放入什么。
我做了那个代码:
public class Split {
public static void main(String[] args) {
String str="This is a string\nthis is the next line.\nHello World.";
String[] arrOfStr = str.split("\n");
System.out.println(arrOfStr);
}
}
但是结果是[Ljava.lang.String; @ 36baf30c我不明白。
你并不需要传递limit
到String#split
如果要拆分的所有事件\n
。要显示数组的内容(而不是引用),可以使用Arrays.toString
。
String str = "This is a string\nthis is the next line.\nHello World.";
String[] arrOfStr = str.split("\n");
System.out.println(Arrays.toString(arrOfStr));
输出:
[This is a string, this is the next line., Hello World.]
要查看limit
参数的作用,可以编写for -loop并观察如下结果:
String str = "This is a string\nthis is the next line.\nHello World.";
for (int limit = 0; limit < 4; limit++) {
String[] arrWithLimit = str.split("\n", limit);
System.out.println(limit + ": " + Arrays.toString(arrWithLimit));
}
输出:
0: [This is a string, this is the next line., Hello World.]
1: [This is a string
this is the next line.
Hello World.]
2: [This is a string, this is the next line.
Hello World.]
3: [This is a string, this is the next line., Hello World.]
您可以看到该参数限制了所应用的拆分数量。0
考虑所有事件(与不存在相同limit
)。在中1
,只有1个元素;在中arrWithLimit
,2
有2个元素。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句