tags:

views:

120

answers:

6

Hello,

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!

+3  A: 

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.

Alois Cochard
But this doesn't even work... it gives `"re you"` and `"e you"`
aioobe
@Torres, no, that would miss the middle character. (and throw an exception on the empty string)
aioobe
Alois's answer is incorrect and Torres is also incorrect. The correct answer is `String s = "How are you?"; String first = s.substring(0, s.length() / 2); String second = s.substring(s.length() / 2);`
Ralph
I give some hints, and explaining how the method work. It wasn't intended to cover perfectly the requirements, sorry. Now corrected ...
Alois Cochard
+1  A: 

Use String.substring(int), and String.substring(int, int) method.

int cutPos = s.length()/2;
String s1 = s.substring(0, cutPos);
String s2 = s.substring(cutPos, s.length()); //which is essentially the same as
//String s2 = s.substring(cutPos);
The Elite Gentleman
You've made a mistake: substring(beginPosition). so substring(cutPos) is not the same as substring(0, cutPos)
Yuri.Bulkin
Instead of `s.substring(cutPos + 1, s.length());`, better use `s.substring(cutPos + 1);`
mklhmnn
@Yuri Bulkin, thanks! I fixed my problem.
The Elite Gentleman
@mklhmm, true....I've edited my post to show the 2.
The Elite Gentleman
Sorry, this does't work either. gives `"How a"` and `"e you"` (provided you change `cutPos -` to `cutPos =`
aioobe
@aioobe, thanks....the cutPos + 1 on the s2 is what caused the problem. I fixed it
The Elite Gentleman
@The Elite Gentleman, you may want to change the first `-` into a `=` too.
aioobe
@aioobe, thanks...I'm slow today...I don't know why though.
The Elite Gentleman
+4  A: 

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

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

aioobe
Downvoter, care to explain?
aioobe
+2  A: 
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 "".

BigMac66
+1  A: 

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

seanizer
+1  A: 

I did not find anywhere an answer.

The first place you should always look is at the javadocs for the class in question: in this case java.lang.String. The javadocs

  • can be browsed online on the Oracle website (e.g. at http://download.oracle.com/javase/6/docs/api/),
  • are included in any Sun/Oracle Java SDK distribution,
  • are probably viewable in your Java IDE, and
  • and be found using a Google search.
Stephen C