Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 698
Ewen Avatar asked Aug 30 '12 15:08

Ewen


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

like image 144
Baz Avatar answered Oct 17 '22 03:10

Baz


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();
    }
}
like image 45
corsiKa Avatar answered Oct 17 '22 02:10

corsiKa