这是一个解决方案:
public static void main(String [] args)
{
String test = "test lala idea<I want potatoes<";
String piecesOfTest[] = test.split("<");
// if you need to split by a dot you need to use "\\."
System.out.println(piecesOfTest[0]);
// prints "test lala idea"
System.out.println(piecesOfTest[1]);
// prints "I want potatoes"
// Here goes a for loop in case you want to
// print the array position by position
}
在这种情况下, split 采用“test lala idea”(从开始到第一个')并保存在piecesOfTest[0]中(这只是一个解释)。然后获取“我想要土豆”(从第一个 ')并将其保存到piecesOfTest1,因此数组的下一个位置.
如果您想在循环中打印此内容,您可以按照以下步骤操作(此循环应仅在运行 .split(regex) 之后放置:
for(int i = 0; i < piecesOfTest.length; i++){
// 'i' works as an index, so it will be run for i=0, and i=1, due to the condition
// (run while) `i < piecesOfTest.length`, in this case piecesOfTest.length will be 2.
// but will never be run for i=2, due to (as I said) the condition of run while i < 2
System.out.println(piecesOfTest[i]);
}
只是为了学习,正如ambigram_maker 所说,您还可以使用“for each”结构:
for (String element: piecesOfTest)
// for each loop, each position of the array is stored inside element
// So in the first loop piecesOfTest[0] will be stored inside element, for the
// second loop piecesOfTest[1] will be stored inside element, and so on
System.out.println(element);
}