如何将列表中的字符串拆分为字符串数组

huangapple go评论72阅读模式
英文:

How to split strings of list into string array

问题

我有一个包含("One.two.three", "one.two.four")的列表。我想将它们保存在一个字符串数组中,如下所示:

One
two
three
one
two
four

背后的逻辑是什么?

英文:

I have a list that contains ("One.two.three", "one.two.four"). I want to save then in a string array as

One
two
three
one
two
four

What is the logic behind it?

答案1

得分: 3

你应该使用Java 8来运行这段代码。只需将这些字符串按“.”拆分。
Java的split方法需要正则表达式来匹配“.”,所以你需要使用“\.”来匹配“.”。然后将数组转换为列表,然后将单词添加到列表中。

public static void main(String[] args) {
    List<String> words = new ArrayList<String>();
    List<String> list = new ArrayList<String>();
    list.add("One.two.three");
    list.add("one.two.four");
    list.stream().forEach(str -> {
        words.addAll(Arrays.asList(str.split("\\.")));
    });
    System.out.println(words.toString());
    //output : [One, two, three, one, two, four]
}
英文:

You should be using java 8 to run this code. Just take those strings and split them on "."
split method of java need regex so to match "." you need "\.".Then transform array to list, then add words to list.

public static void main(String[] args) {
		List&lt;String&gt; words = new ArrayList&lt;String&gt;();
		List&lt;String&gt; list = new ArrayList&lt;String&gt;();
		list.add(&quot;One.two.three&quot;);
		list.add(&quot;one.two.four&quot;);
		list.stream().forEach(str -&gt; {
			words.addAll(Arrays.asList(str.split(&quot;\\.&quot;)));
		});
		System.out.println(words.toString());
        //output : [One, two, three, one, two, four]
	}

答案2

得分: 3

你可以在Java 8及更高版本中使用flatmap,如下所示:

String[] words = list.stream().flatMap(str -> Arrays.stream(str.split("\\."))).toArray(String[]::new);
英文:

For java 8+, you can use flatmap as -

String[] words = list.stream().flatMap(str -&gt; Arrays.stream(str.split(&quot;\\.&quot;))).toArray(String[]::new);

答案3

得分: 1

如果您在谈论静态数组,重要的是知道数组大小,以避免"索引超出范围"的异常。

这种方式,我提供了一个解决方案,它计算单词的数量,然后创建输出s数组来保存每个单词。

我们可以使用String.split()函数来获取要添加到输出数组的单词:

String[] a = {"One.two.three", "one.two.four"};
int count = 0;
for (int i = 0; i < a.length; i++) { //如果您知道所需的数组大小,请跳过此循环
    count += a[i].split("\\.").length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i < a.length; i++) {
    String[] b = a[i].split("\\.");
    for (int j = 0; j < b.length; j++) {
        s[k++] = b[j];
    }
}
for (int i = 0; i < s.length; i++) {
    System.out.println(s[i]);
}
英文:

If you are talking about the static arrays it is important to know array size to avoid "index is out of bounds" exception.

This way, I provide the solution that counts the number of words and then creates output s array to save every word.

We can use the String.split() function to get the single words we adding to output array:

String[] a = {&quot;One.two.three&quot;, &quot;one.two.four&quot;};
int count = 0;
for (int i = 0; i &lt; a.length; i++) { //skip this loop if you know the wanted array size
    count += a[i].split(&quot;\\.&quot;).length;
}
String[] s = new String[count];
int k = 0;
for (int i = 0; i &lt; a.length; i++) {
    String[] b = a[i].split(&quot;\\.&quot;);
    for (int j = 0; j &lt; b.length; j++) {
        s[k++] = b[j];
    }
}
for (int i = 0; i &lt; s.length; i++) {
    System.out.println(s[i]);
}

答案4

得分: 1

**FOR JAVA 1.8+**

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("One.two.three");
    list.add("One.two.four");
    
    List<String> newList = new ArrayList<String>();
    list.forEach(string -> {
        String[] stringArr = string.split("\\.");
        for (String innerString : stringArr) {
            newList.add(innerString);
        } 
    });
    
    String[] stringArr = newList.toArray(new String[newList.size()]);
    System.out.println(Arrays.toString(stringArr));
}

**UPTO JAVA 1.7**

public static void main(String[] args) {
    List<String> list = new ArrayList<String>();
    list.add("One.two.three");
    list.add("One.two.four");
    
    List<String> newList = new ArrayList<String>();
    for (String string : list) {
        String[] stringArr = string.split("\\.");
        for (String innerString : stringArr) {
            newList.add(innerString);
        } 
    }
    
    String[] stringArr = newList.toArray(new String[newList.size()]);
    System.out.println(Arrays.toString(stringArr));
}
英文:

Try this.

FOR JAVA 1.8+

public static void main(String[] args) {
List&lt;String&gt; list = new ArrayList&lt;String&gt;();
list.add(&quot;One.two.three&quot;);
list.add(&quot;One.two.four&quot;);
List&lt;String&gt; newList = new ArrayList&lt;String&gt;();
list.forEach(string -&gt; {
String[] stringArr = string.split(&quot;\\.&quot;);
for (String innerString : stringArr) {
newList.add(innerString);
} 
});
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}

UPTO JAVA 1.7

public static void main(String[] args) {
List&lt;String&gt; list = new ArrayList&lt;String&gt;();
list.add(&quot;One.two.three&quot;);
list.add(&quot;One.two.four&quot;);
List&lt;String&gt; newList = new ArrayList&lt;String&gt;();
for (String string : list) {
String[] stringArr = string.split(&quot;\\.&quot;);
for (String innerString : stringArr) {
newList.add(innerString);
} 
}
String[] stringArr = newList.toArray(new String[newList.size()]);
System.out.println(Arrays.toString(stringArr));
}

答案5

得分: 1

如果您的Java版本低于8,您可以使用以下代码片段:

public class Main {
    public static void main(String[] args) throws Exception {
        List<String> originalList = new ArrayList();
        List<String> finalList = new ArrayList();
        originalList.add("One.two.three");
        originalList.add("One.two.four");

        for(String myString : originalList) {
            //双斜杠用于转义点
            finalList.addAll(Arrays.asList(myString.split("\\.")));
        }

        //从列表创建一个数组
        String[] theArray = finalList.toArray(new String[finalList.size()]);
    }
}

最后,'theArray' 将包含:

[One, two, three, one, two, four]

查看有关[将字符串拆分为部分][1]的文档。

[1]: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)
英文:

If you are below Java 8 you can use this snippet:

public class Main {
public static void main(String[] args) throws Exception {
List&lt;String&gt; originalList = new ArrayList();
List&lt;String&gt; finalList = new ArrayList();
originalList.add(&quot;One.two.three&quot;);
originalList.add(&quot;One.two.four&quot;);
for(String myString : originalList) {
//The \\ is to scape the dot
finalList.addAll(Arrays.asList(myString.split(&quot;\\.&quot;)));
}
//Creates an array from the list
String[] theArray = finalList.toArray(new String[finalList.size()]);
}
}

Finally, theArray will contain:

[One, two, three, one, two, four]

Take a look at the docs about splitting an string into parts

huangapple
  • 本文由 发表于 2020年7月21日 23:58:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/63018406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定