java 如何将字符串的 ArrayList 转换为字符数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35173887/
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-11-02 23:50:11  来源:igfitidea点击:

How to convert ArrayList of Strings to char array

javaarraylist

提问by Baurzhan Kozhaev

The following code converts ArrayList<String>to char[]and print output which appears as [back, pack]. Here, the char[]includes ','and ' '. Is there a way to do it in another way to get rid of comma and space?

以下代码转换ArrayList<String>char[]并打印输出,显示为[back, pack]. 在这里,char[]包括','' '。有没有办法以另一种方式摆脱逗号和空格?

ArrayList<String> list = new ArrayList<String>();
list.add("back");
list.add("pack");

char[] chars = list.toString().toCharArray();

for (char i : chars){
   System.out.print(i);
}

回答by hotkey

You can do it by joining the Strings in your ArrayList<String>and then getting char[]from the result:

您可以通过String在您的s 中加入sArrayList<String>然后char[]从结果中获得:

char[] chars = list.stream().collect(Collectors.joining()).toCharArray();

Here .stream.collect(Collectors.joining())part is Java 8 Stream way to join a sequence of Stringsinto one. See: Collectors.joining()docs.

这里.stream.collect(Collectors.joining())部分是 Java 8 Stream 将序列连接Strings为一个的方式。请参阅:Collectors.joining()文档。

If you want any delimiter between the parts in the result, use Collectors.joining(delimiter)instead.

如果您希望结果中的部分之间有任何分隔符,请Collectors.joining(delimiter)改用。

There's also an overload which adds prefix and suffix to the result, for example, if you want [and ]in it, use Collectors.joining("", "[", "]").

还有一个重载,它为结果添加前缀和后缀,例如,如果你想要[]在其中使用Collectors.joining("", "[", "]").

回答by Shomil Khare

Just replace the this line

只需更换这一行

char[] chars = list.toString().toCharArray();

with below two lines

有以下两行

String str=list.toString().replaceAll(",", "");
char[] chars = str.substring(1, str.length()-1).replaceAll(" ", "").toCharArray();

回答by mohammedkhan

Your toStringmethod on listis what is adding the comma and space, it's a Stringrepresentation of your list. As listis a collection of Strings you don't need to call toStringon it, just iterate through the collection converting each Stringinto an array of chars using toCharArray(I assume you will probably want to add all the chars of all the Strings together).

您的toString方法list是添加逗号和空格,它String是您的list. 作为slist的集合,String您不需要调用toString它,只需遍历集合,使用将每个集合转换String为字符数组toCharArray(我假设您可能希望将所有字符串的所有字符添加在一起)。

回答by Anand Pandey

String to charArray in Java Code:

Java代码中的字符串到charArray:

ArrayList<String> list = new ArrayList<String>();
ArrayList<Character> chars = new ArrayList<Character>();
list.add( "back" );
list.add( "pack" );
for ( String string : list )
{
    for ( char c : string.toCharArray() )
    {
        chars.add( c );
    }
}
System.out.println( chars );

回答by bodo

Just an example how should you resolved large list to array copy. Beware number of characters must be less then Integer.MAX. This code is just an example how it could be done. There are plenty of checks that one must implement it to make that code works properly.

只是一个例子,你应该如何将大列表解析为数组副本。注意字符数必须小于 Integer.MAX。此代码只是如何完成的示例。有很多检查必须实现它才能使代码正常工作。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class WrappedList {

    //Or replace with some better counter
    int totalCharCount = 0;
    final List<String> list;

    public WrappedList() {
        this(new ArrayList<String>());
    }

    public WrappedList(final List<String> list) {
        this.list = list;
    }

    public void add(final String toAdd) {
        if(toAdd != null) {
            totalCharCount += toAdd.length();
            this.list.add(toAdd);
        }
    }

    public List<String> getList() {
        return Collections.unmodifiableList(list);
    }

    public char[] toCharArray() {
        return this.toCharArray(this.totalCharCount);
    }


    public char[] toCharArray(final int charCountToCopy) {
        final char[] product = new char[charCountToCopy];
        int buffered = 0;
        for (String string : list) {
            char[] charArray = string.toCharArray();
            System.arraycopy(charArray, 0, product, buffered, charArray.length);
            buffered += charArray.length;
        }
        return product;
    }

    //Utility method could be used  also as stand-alone class
    public char[] toCharArray(final List<String> all) {
        int size = all.size();
        char[][] cpy = new char[size][];
        for (int i = 0; i < all.size(); i++) {
            cpy[i] = all.get(i).toCharArray();
        }
        int total = 0;
        for (char[] cs : cpy) {
            total += cs.length;
        }
        return this.toCharArray(total);
    }

    public static void main(String[] args) {
        //Add String iteratively
        WrappedList wrappedList = new WrappedList();
        wrappedList.add("back");
        wrappedList.add("pack");
        wrappedList.add("back1");
        wrappedList.add("pack1");
        final char[] charArray = wrappedList.toCharArray();
        System.out.println("Your char array:");
        for (char c : charArray) {
            System.out.println(c);
        }

        //Utility method one time for all, should by used in stand-alone Utility class
        System.out.println("As util method");
        System.out.println(wrappedList.toCharArray(wrappedList.getList()));
    }

}

See also: system-arraycopy-than-a-for-loop-for-copying-arrays

另请参阅:system-arraycopy-than-a-for-loop-for-copying-arrays