[英]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.