How to split a String by space

2018-12-31 18:35发布

I need to split my String by spaces. For this I tried:

str = "Hello I'm your String";
String[] splited = str.split(" ");

But it doesn't seem to work.

14条回答
大哥的爱人
2楼-- · 2018-12-31 19:03

Use Stringutils.split() to split the string by whites paces. For example StringUtils.split("Hello World") returns "Hello" and "World";

In order to solve the mentioned case we use split method like this

String split[]= StringUtils.split("Hello I'm your String");

when we print the split array the output will be :

Hello

I'm

your

String

For complete example demo check here

查看更多
心情的温度
3楼-- · 2018-12-31 19:07

if somehow you don't wanna use String split method then you can use StringTokenizer class in Java as..

    StringTokenizer tokens = new StringTokenizer("Hello I'm your String", " ");
    String[] splited = new String[tokens.countTokens()];
    int index = 0;
    while(tokens.hasMoreTokens()){
        splited[index] = tokens.nextToken();
        ++index;
    }
查看更多
高级女魔头
4楼-- · 2018-12-31 19:11

I do believe that putting a regular expression in the str.split parentheses should solve the issue. The Java String.split() method is based upon regular expressions so what you need is:

str = "Hello I'm your String";
String[] splitStr = str.split("\\s+");
查看更多
浪荡孟婆
5楼-- · 2018-12-31 19:12

Here is a method to trim a String that has a "," or white space

private String shorterName(String s){
        String[] sArr = s.split("\\,|\\s+");
        String output = sArr[0];

        return output;
    }
查看更多
深知你不懂我心
6楼-- · 2018-12-31 19:12

Very Simple Example below:

Hope it helps.

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
查看更多
登录 后发表回答