Splitting string on multiple spaces in java [duplicate]

人盡茶涼 提交于 2020-05-07 11:48:33

问题


Possible Duplicate:
How to split a String by space

I need help while parsing a text file. The text file contains data like

This is     different type   of file.
Can not split  it    using ' '(white space)

My problem is spaces between words are not similar. Sometimes there is single space and sometimes multiple spaces are given.

I need to split the string in such a way that I will get only words, not spaces.


回答1:


str.split("\\s+") would work. The + at the end of the regular-expression, would treat multiple spaces the same as a single space. It returns an array of strings (String[]) without any " " results.




回答2:


You can use Quantifiers to specify the number of spaces you want to split on: -

    `+` - Represents 1 or more
    `*` - Represents 0 or more
    `?` - Represents 0 or 1
`{n,m}` - Represents n to m

So, \\s+ will split your string on one or more spaces

String[] words = yourString.split("\\s+");

Also, if you want to specify some specific numbers you can give your range between {}:

yourString.split("\\s{3,6}"); // Split String on 3 to 6 spaces



回答3:


Use a regular expression.

String[] words = str.split("\\s+");



回答4:


you can use regex pattern

public static void main(String[] args)
{
    String s="This is     different type   of file.";
    String s1[]=s.split("[ ]+");
    for(int i=0;i<s1.length;i++)
    {
        System.out.println(s1[i]);
    }
}

output

This
is
different
type
of
file.



回答5:


you can use
replaceAll(String regex, String replacement) method of String class to replace the multiple spaces with space and then you can use split method.




回答6:


String spliter="\\s+";
String[] temp;
temp=mystring.split(spliter);



回答7:


I am giving you another method to tockenize your string if you dont want to use the split method.Here is the method

public static void main(String args[]) throws Exception
{
    String str="This is     different type   of file.Can not split  it    using ' '(white space)";
    StringTokenizer st = new StringTokenizer(str, " "); 
    while(st.hasMoreElements())
    System.out.println(st.nextToken());
}
 }


来源:https://stackoverflow.com/questions/13081527/splitting-string-on-multiple-spaces-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!