如何从第一个空格中拆分字符串(仅限Java)
我尝试使用string.Index和string.length拆分字符串,但出现一个错误,字符串超出范围。我怎样才能解决这个问题如何从第一个空格中拆分字符串(仅限Java),java,string,Java,String,我尝试使用string.Index和string.length拆分字符串,但出现一个错误,字符串超出范围。我怎样才能解决这个问题 while (in.hasNextLine()) { String temp = in.nextLine().replaceAll("[<>]", ""); temp.trim(); String nickname = temp.substring(temp.indexOf(' ')); String content
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);
while(在.hasNextLine()中){
字符串temp=in.nextLine().replaceAll(“[]”,“”);
温度微调();
字符串昵称=临时子字符串(临时索引(“”));
字符串内容=临时子字符串(“”+临时长度()-1);
系统输出打印项次(内容);
必须与此相关:
String nickname = temp.substring(0, temp.indexOf(' '));
String content = temp.substring(temp.indexOf(' ') + 1);
使用带有限制的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
split接受限制模式应用次数的限制输入
默认情况下,split方法根据给定的正则表达式创建n个数组。
但是,如果您想限制拆分后创建的数组的数量,而不是作为整数参数的传递秒参数。考虑如果
temp
中没有'
,会发生什么情况,然后处理这种情况。'
的ASCII值为32,因此'+temp.length()-1
将大于32,我怀疑temp.length()
是否大于32。您需要使用temp.indexOf(“”)
而不仅仅是'
,并且不要添加temp.length()-1
。这应该是可以接受的答案。
string.split(" ",2)
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