如何仅从第一个空格出现的 Java 中拆分字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39732481/
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
How to split a string from the first space occurrence only Java
提问by Dimitrios Sria
I tried to split a string using string.Index and string.length but I get an error that string is out of range. How can I fix that?
我尝试使用 string.Index 和 string.length 拆分字符串,但出现字符串超出范围的错误。我该如何解决?
while (in.hasNextLine()) {
String temp = in.nextLine().replaceAll("[<>]", "");
temp.trim();
String nickname = temp.substring(temp.indexOf(' '));
String content = temp.substring(' ' + temp.length()-1);
System.out.println(content);
采纳答案by Alex Chermenin
Must be some around this:
必须是一些围绕这个:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
回答by Steve Owens
Use the java.lang.String split function with a limit.
使用带有限制的 java.lang.String 拆分函数。
String foo = "some string with spaces";
String parts[] = foo.split(" ", 2);
System.out.println(String.format("cr: %s, cdr: %s", parts[0], parts[1]));
You will get:
你会得到:
cr: some, cdr: string with spaces
回答by Sid
string.split(" ",2)
split takes a limit input restricting the number of times the pattern is applied.
split 采用限制输入来限制应用模式的次数。
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
回答by Dinesh Ubale
String string = "This is test string on web";
String splitData[] = string.split("\s", 2);
Result ::
splitData[0] => This
splitData[1] => is test string
String string = "This is test string on web";
String splitData[] = string.split("\s", 3);
Result ::
splitData[0] => This
splitData[1] => is
splitData[1] => test string on web
By default split method create n number's of arrays on the basis of given regex. But if you want to restrict number of arrays to create after a split than pass second argument as an integer argument.
默认情况下,split 方法根据给定的正则表达式创建 n 个数组。但是,如果您想限制拆分后要创建的数组数量,而不是将第二个参数作为整数参数传递。