How can I split a string in to multiple parts?

I have a string with several words separated by spaces, e.g. "firstword second third", and an ArrayList. I want to split the string into several pieces, and add the 'piece' strings to the ArrayList.

For example,"firstword second third" can be split to three separate strings , so the ArrayList would have 3 elements; "1 2 3 4" can be split into 4 strings, in 4 elements of the ArrayList. See the code below:

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 ....
}

Please leave a comment if you dont get what I mean or I should fix some errors in this post. Thanks for your time!

Answers


You can split the String at the spaces using split():

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

Afterwards iterate over the array and add the individual parts (if !"".equals(parts[i]) to the list.


If you want to split on one space, you can use .split(" ");. If you want to split on all spaces in a row, use .split(" +");.

Consider the following example:

class SplitTest {
    public static void main(String...args) {
        String s = "This is a  test"; // note two spaces between 'a' and 'test'
        String[] a = s.split(" ");
        String[] b = s.split(" +");
        System.out.println("a: " + a.length);
        for(int i = 0; i < a.length; i++) {
            System.out.println("i " + a[i]);
        }
        System.out.println("b: " + b.length);
        for(int i = 0; i < b.length; i++) {
            System.out.println("i " + b[i]);
        }
    }
}

If you are worried about non-standard spaces, you can use "\\s+" instead of " +", as "\\s" will capture any white space, not just the 'space character'.

So your separate and add method becomes:

void separateAndAdd(String raw) {
    String[] tokens = raw.split("\\s+");
    theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
    for(String s : tokens) {
        theArray.add(s);
    }

}

Here's a more complete example - note that there is a small modification in the separateAndAdd method that I discovered during testing.

import java.util.*;
class SplitTest {
    public static void main(String...args) {
        SplitTest st = new SplitTest();
        st.separateAndAdd("This is a test");
        st.separateAndAdd("of the emergency");
        st.separateAndAdd("");
        st.separateAndAdd("broadcast system.");

        System.out.println(st);
    }

    ArrayList<String> theArray = new ArrayList<String>();

    void separateAndAdd(String raw) {
        String[] tokens = raw.split("\\s+");
        theArray.ensureCapacity(theArray.size() + tokens.length); // prevent unnecessary resizes
        for(String s : tokens) {
            if(!s.isEmpty()) theArray.add(s);
        }
    }

    public String toString() {
        StringBuilder sb = new StringBuilder();
        for(String s : theArray)
            sb.append(s).append(" ");
        return sb.toString().trim();
    }
}

Do this:

thearray = new ArrayList<String>(Arrays.asList(notseparated.split(" ")));

or if thearray already instantiated

thearray.addAll(Arrays.asList(notseparated.split(" ")));

I would suggest using the

apache.commons.lang.StringUtils library.

It is the easiest and covers all the different conditions you can want int he spliting up of a string with minimum code.

Here is a reference to the split method : Split Method

you can also refer to the other options available for the split method on the same link.


You can do that using .split() try this

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

If you want to split the string in different parts, like here i am going to show you that how i can split this string 14-03-2016 in day,month and year.

 String[] parts = myDate.split("-");
           day=parts[0];
           month=parts[1];
           year=parts[2];

try this: string to 2 part:

public String[] get(String s){
    int l = s.length();
    int t = l / 2;
    String first = "";
    String sec = "";
    for(int i =0; i<l; i++){
        if(i < t){
            first += s.charAt(i);
        }else{
            sec += s.charAt(i);
        }
    }
    String[] result = {first, sec};
    return result;
}

example:

String s = "HelloWorld";
String[] res = get(s);
System.out.println(res[0]+" "+res[1])

output:

Hello World

Need Your Help

BaseInterpolator cannot be resolved to a type

android sdk include

As the title said, "BaseInterpolator" cannot be resolved to a type and I couldn't include it through

Browserify to minify and concat files

javascript node.js browserify

I have a purely web-based app (ie no Node server) and I want to be able to bundle all my JS files and CSS files for each page of the web app.