Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split a string by position in Java

Tags:

java

string

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!

like image 372
Roger22 Avatar asked Oct 26 '10 11:10

Roger22


4 Answers

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);
  • http://www.roseindia.net/java/beginners/SubstringExample.shtml

And are you expecting string with odd length ? in this case you must add logic to handle this case correctly.

like image 30
Alois Cochard Avatar answered Nov 14 '22 12:11

Alois Cochard


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

like image 61
aioobe Avatar answered Nov 14 '22 13:11

aioobe


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

like image 41
BigMac66 Avatar answered Nov 14 '22 13:11

BigMac66


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']

like image 4
Sean Patrick Floyd Avatar answered Nov 14 '22 11:11

Sean Patrick Floyd