[英]How to split a string from the first space occurrence only Java
我尝试使用 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);
使用带有限制的 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]));
你会得到:
cr: some, cdr: string with spaces
必须是一些围绕这个:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
string.split(" ",2)
split 采用限制输入来限制应用模式的次数。
http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)
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
默认情况下,split 方法根据给定的正则表达式创建 n 个数组。 但是,如果您想限制拆分后要创建的数组数量,而不是将第二个参数作为整数参数传递。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.