我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
我需要用空格分割我的字符串。 为此我试过:
str = "Hello I'm your String";
String[] splited = str.split(" ");
但这似乎并不奏效。
当前回答
你可以使用下面的代码分离字符串:
String theString="Hello world";
String[] parts = theString.split(" ");
String first = parts[0];//"hello"
String second = parts[1];//"World"
其他回答
下面是一个非常简单的例子:
希望能有所帮助。
String str = "Hello I'm your String";
String[] splited = str.split(" ");
var splited = str.split(" ");
var splited1=splited[0]; //Hello
var splited2=splited[1]; //I'm
var splited3=splited[2]; //your
var splited4=splited[3]; //String
Try
String[] splited = str.split("\\s");
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
你所拥有的应该有用。但是,如果所提供的空格默认为…别的吗?你可以使用空白正则表达式:
str = "Hello I'm your String";
String[] splited = str.split("\\s+");
这将导致任意数量的连续空格将字符串分割为令牌。
使用Stringutils.split()按白色步长分割字符串。例如StringUtils。split("Hello World")返回"Hello"和"World";
为了解决上述情况,我们采用了这样的分割方法
String split[]= StringUtils.split("Hello I'm your String");
当我们打印拆分数组时,输出将是:
你好
I'm
your
字符串
完整的示例演示检查这里
另一种方法是:
import java.util.regex.Pattern;
...
private static final Pattern SPACE = Pattern.compile(" ");
String[] arr = SPACE.split(str); // str is the string to be split
在这里看到的