gpt4 book ai didi

java - 如何将一个字符串分成多个部分?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:42:06 25 4
gpt4 key购买 nike

我有一个由空格分隔的几个单词的字符串,例如“firstword second third”,和一个ArrayList。我想将字符串分成几部分,并将“部分”字符串添加到 ArrayList。

例如,"firstword second third"可以拆分为三个单独的字符串,因此 ArrayList 将有 3 个元素; "1 2 3 4"可以拆分成4个字符串,在ArrayList的4个元素中。请看下面的代码:

public void separateAndAdd(String notseparated) {
for(int i=0;i<canBeSepartedinto(notseparated);i++{
//what should i put here in order to split the string via spaces?
thearray.add(separatedstring);
}
}

public int canBeSeparatedinto(String string)
//what do i put here to find out the amount of spaces inside the string?
return ....
}

如果您不明白我的意思,请发表评论,否则我应该修正这篇文章中的一些错误。谢谢你的时间!

最佳答案

您可以使用 split() 在空格处拆分字符串:

String[] parts = inputString.split(" ");

然后遍历数组并将各个部分 (if !"".equals(parts[i]) 添加到列表中。

关于java - 如何将一个字符串分成多个部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12200514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com