Java 拆分以空格分隔的列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3214002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 17:28:53  来源:igfitidea点击:

Splitting a space separated list

javastring

提问by Wram

This is a common task I'm facing: splitting a space separated list into a headelement and an array containing the tailelements. For example, given this string:

这是我面临的一项常见任务:将一个空格分隔的列表拆分为一个元素和一个包含元素的数组。例如,给定这个字符串:

the quick brown fox

We want:

我们想要:

"the"
["quick","brown","fox"]

.. in two different variables. The first variable should be a string, and the second an array. I'm looking for an elegantway to do this (preferably in Java).

.. 在两个不同的变量中。第一个变量应该是一个字符串,第二个变量应该是一个数组。我正在寻找一种优雅的方式来做到这一点(最好是在 Java 中)。

采纳答案by Alterscape

For certain values of elegant:

对于某些优雅的值:

String input = "The quick brown fox";
String[] elements = input.split(" ");
String first = elements[0];
String[] trailing = Arrays.copyOfRange(elements,1,elements.length);

I can't think of a way to do it with less code...

我想不出用更少的代码来做到这一点的方法......

回答by Jeff

Use StringTokenizerand a while loop to step through each element. Inside the loop, you can get the first element and put the rest into an array.

使用StringTokenizer和 while 循环遍历每个元素。在循环内部,您可以获取第一个元素并将其余元素放入数组中。

Edit: Oh, I guess StringTokenizer is a "legacy" class (though it still works).

编辑:哦,我猜 StringTokenizer 是一个“遗留”类(尽管它仍然有效)。

The recommended way is now to use String.split(). That will give you a String[] containing your elements. From there it should be trivial to get the first element and also create an array out of the remaining elements.

现在推荐的方法是使用String.split()。这会给你一个 String[] 包含你的元素。从那里获取第一个元素并从剩余元素中创建一个数组应该是微不足道的。

回答by Salil

str= "the quick brown fox"
  pqr = str.split(" ")

回答by Carl Smotricz

Well, you get most of what you want with

嗯,你得到了大部分你想要的

String[] pieces = "how now brown cow".split("\s") 

or so. Your result will be an array of Strings.

或者。您的结果将是一个字符串数组。

If you really, really want the first item separate from the rest, you can then do something like:

如果您真的,真的希望第一项与其余项分开,那么您可以执行以下操作:

String head = pieces[0];
String[] tail = new String[pieces.length - 1];
System.arraycopy(pieces, 1, tail, 0, tail.length);

...done.

...完毕。

回答by BalusC

You could make use of String#split()taking a limit as 2nd argument.

您可以使用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]

回答by polygenelubricants

The most elegant is probably to use String.splitto get a String[], then using Arrays.asListto turn it into a List<String>. If you really need a separate list minus the head, just use List.subList.

最优雅的可能是使用String.splitget a String[],然后使用Arrays.asList将其变成 a 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"

Using a Listallows you to take advantage of the rich features provided by Java Collections Framework.

使用 aList允许您利用 Java Collections Framework 提供的丰富功能。

See also

也可以看看

回答by Carl Manaster

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);
        }

    }
}

回答by Thorbj?rn Ravn Andersen

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));
    }

Would have been much easier in Haskell :)

在 Haskell 中会容易得多:)