I did not find anywhere an answer.. If i have: String s = "How are you"?
How can i split this into two strings, so first string containing from 0..s.length()/2 and the 2nd string from s.length()/2+1..s.length()?
Thanks!
You can use 'substring(start, end)', but of course check if string isn't null before:
String first = s.substring(0, s.length() / 2);
String second = s.substring(s.length() / 2);
And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.
This should do:
String s = "How are you?";
String first = s.substring(0, s.length() / 2);  // gives "How ar"
String second = s.substring(s.length() / 2);    // gives "e you?"
String.substring(int i) with one argument returns the substring beginning at position i
String.substring(int i, int j) with two arguments returns the substring beginning at i and ending at j-1.
(Note that if the length of the string is odd, second will have one more character than first due to the rounding in the integer division.)
String s0 = "How are you?";
String s1 = s0.subString(0, s0.length() / 2);
String s2 = s0.subString(s0.length() / 2);
So long as s0 is not null.
EDIT
This will work for odd length strings as you are not adding 1 to either index. Surprisingly it even works on a zero length string "".
Here's a method that splits a string into n items by length. (If the string length can not exactly be divided by n, the last item will be shorter.)
public static String[] splitInEqualParts(final String s, final int n){
    if(s == null){
        return null;
    }
    final int strlen = s.length();
    if(strlen < n){
        // this could be handled differently
        throw new IllegalArgumentException("String too short");
    }
    final String[] arr = new String[n];
    final int tokensize = strlen / n + (strlen % n == 0 ? 0 : 1);
    for(int i = 0; i < n; i++){
        arr[i] =
            s.substring(i * tokensize,
                Math.min((i + 1) * tokensize, strlen));
    }
    return arr;
}
Test code:
/**
 * Didn't use Arrays.toString() because I wanted to have quotes.
 */
private static void printArray(final String[] arr){
    System.out.print("[");
    boolean first = true;
    for(final String item : arr){
        if(first) first = false;
        else System.out.print(", ");
        System.out.print("'" + item + "'");
    }
    System.out.println("]");
}
public static void main(final String[] args){
    printArray(splitInEqualParts("Hound dog", 2));
    printArray(splitInEqualParts("Love me tender", 3));
    printArray(splitInEqualParts("Jailhouse Rock", 4));
}
Output:
['Hound', ' dog']
['Love ', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With