[英]Splitting a space separated list
這是我面臨的一項常見任務:將空格分隔列表拆分為head元素和包含tail元素的數組。 例如,給定此字符串:
the quick brown fox
我們想要:
"the"
["quick","brown","fox"]
..在兩個不同的變量。 第一個變量應該是一個字符串,第二個變量應該是一個數組。 我正在尋找一種優雅的方式(最好用Java)。
對於某些優雅的價值觀:
String input = "The quick brown fox";
String[] elements = input.split(" ");
String first = elements[0];
String[] trailing = Arrays.copyOfRange(elements,1,elements.length);
我想不出用更少的代碼來做到這一點的方法......
最優雅的可能是使用String.split
來獲取String[]
,然后使用Arrays.asList
將其轉換為List<String>
。 如果你真的需要一個單獨的列表減去頭部,只需使用List.subList
。
String text = "the quick brown fox";
List<String> tokens = Arrays.asList(text.split("\\s+"));
String head = tokens.get(0);
List<String> body = tokens.subList(1, tokens.size());
System.out.println(head); // "the"
System.out.println(body); // "[quick, brown, fox]"
System.out.println(body.contains("fox")); // "true"
System.out.println(body.contains("chicken")); // "false"
使用List
可以利用Java Collections Framework提供的豐富功能。
好吧,你得到了你想要的大部分
String[] pieces = "how now brown cow".split("\\s")
或者。 你的結果將是一系列字符串。
如果你真的,真的希望第一個項目與其他項目分開,那么你可以做類似的事情:
String head = pieces[0];
String[] tail = new String[pieces.length - 1];
System.arraycopy(pieces, 1, tail, 0, tail.length);
...完成。
您可以使用String#split()
將限制作為第二個參數。
String text = "the quick brown fox";
String[] parts = text.split(" ", 2);
String headPart = parts[0];
String[] bodyParts = parts[1].split(" ");
System.out.println(headPart); // the
System.out.println(Arrays.toString(bodyParts)); // [quick, brown, fox]
package playground;
import junit.framework.TestCase;
public class TokenizerTest extends TestCase {
public void testTokenize() throws Exception {
String s = "the quick brown fox";
MyThing t = new MyThing(s);
assertEquals("the", t.head);
String[] rest = {"quick", "brown", "fox"};
assertEqualArrays(rest, t.rest);
}
private static void assertEqualArrays(String[] a, String[] b) {
assertEquals(a.length, b.length);
for (int i = 0; i < a.length; i++)
assertEquals(a[i], b[i]);
}
private static class MyThing {
private final String head;
private final String[] rest;
public MyThing(String s) {
String[] array = s.split(" ");
head = array[0];
rest = new String[array.length - 1];
System.arraycopy(array, 1, rest, 0, array.length - 1);
}
}
}
public static void main(String[] args) {
String s = "the quick brown fox";
int indexOf = s.indexOf(' ');
String head = s.substring(0, indexOf);
String[] tail = s.substring(indexOf + 1).split(" +");
System.out.println(head + " : " + Arrays.asList(tail));
}
在Haskell中會容易得多:)
使用StringTokenizer和while循環來逐步執行每個元素。 在循環內部,您可以獲取第一個元素並將其余元素放入數組中。
編輯:哦,我猜StringTokenizer是一個“遺產”類(雖然它仍然有效)。
現在推薦的方法是使用String.split() 。 那會給你一個包含元素的String []。 從那里獲取第一個元素並從剩余元素中創建一個數組應該是微不足道的。
str= "the quick brown fox"
pqr = str.split(" ")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.