gpt4 book ai didi

java - 如何将字符串拆分为单词、空格和换行符?

转载 作者:行者123 更新时间:2023-12-02 13:00:32 25 4
gpt4 key购买 nike

我正在使用 Play 框架并从文本区域获取文本,我想将其拆分为输入的单词、空格和换行符的数组。

Hello World How

Are You

会是这样的

a[0] = "Hello";
a[1] = " ";
a[2] = "World";
a[3] = " ";
a[4] = "How";
a[5] = "\n";
a[6] = "Are";
a[7] = " ";
a[8] = "You";

如果有一个简单的正则表达式方式或类似的东西我很想听听?

最佳答案

试试这个代码:

String str = "Hello World How\nAre You";
String[] inputs = str.split("(?!^)\\b");
for (int i=0; i<inputs.length; i++) {
System.out.println("a[" + i + "] = \"" + inputs[i] + '"');
}

OUTPUT:
a[0] = "Hello"
a[1] = " "
a[2] = "World"
a[3] = " "
a[4] = "How"
a[5] = "
"
a[6] = "Are"
a[7] = " "
a[8] = "You"

关于java - 如何将字符串拆分为单词、空格和换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5643581/

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