gpt4 book ai didi

java - 将用户输入的字符拆分为 ArrayList

转载 作者:行者123 更新时间:2023-11-30 06:17:21 28 4
gpt4 key购买 nike

我目前正在为类(class)编写一个编码项目,我们必须采用逗号分隔的 2-10 个字符列表(仅限字母),并在与给定的字典文本文件进行交叉检查后生成所有可能的单词。

我遇到的问题是,虽然我可以拆分列表并创建一个数组,但我知道改用 ArrayList 会更有用,这就是我遇到问题的地方。

Scanner input = new Scanner(System.in);
String letters = input.nextLine();
input.close();
ArrayList<Letters> Letter = new ArrayList<Letters>();
letters.split(",");
Letter.add();

我不确定应该在 add 函数中放入什么,因为我显然不希望所有字符都作为 ArrayList 的一个索引。我在想也许我应该将字符拆分为单独的字符串对象,但我不确定如何实现。有些事情让我想起了我的介绍课上的解析,但仍然遇到了麻烦。

提前感谢您的任何批评和帮助。

最佳答案

当你使用 split 函数时,你的字符串将被转换为一个 String 类型的数组。

Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

source and read about String type

例如:

 String[] splitString = string.split(",");

对于你添加的内容

您可以使用 for 循环遍历拆分后的字符串数组,并将每个元素放入数组列表中,如下所示

for(int i=0; i< splitString.legth; i++)
Letter.add(splitString[i]);

添加是什么意思:

public boolean add(E e) Appends the specified element to the end of this list.

注意:当您使用每个内容字符串数组时,它是一个由 add 函数使用的元素。

注意:字符串是对象,不需要转为对象。

例子:

        String s = "a,b,c"; <---- String is object no need to convert

String[] sp = s.split(",");<---- Array of String is object no need to convert

List<String> l = new ArrayList<>();
for (int i = 0; i < sp.length; i++) {
l.add(sp[i]);
}
for (int i = 0; i < l.size(); i++) {
System.out.print(" " + l.get(i));
}

输出:

a b c

关于java - 将用户输入的字符拆分为 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25939514/

28 4 0