How to split a line by position in Java

I did not find an answer anywhere. If I have: String s = "How are you" ? How can I split this into two lines, so the first line containing from 0..s.length()/2 and the second line from s.length()/2+1..s.length() ?

Thanks!

+6
java string
source share
6 answers

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 string length is odd, second will have another character than the first due to rounding in integer division.)

+17
source share

You can use 'substring (start, end)', but of course, check to see if there has been a line before:

 String first = s.substring(0, s.length() / 2); String second = s.substring(s.length() / 2); 

And do you expect an odd length string? in this case, you must add logic to handle this case correctly.

+5
source share
 String s0 = "How are you?"; String s1 = s0.subString(0, s0.length() / 2); String s2 = s0.subString(s0.length() / 2); 

So far, s0 is not zero.

EDIT

This will work for odd-length rows since you are not adding 1 to the index. It's amazing that it works even with a zero string of length. "

+5
source share

Here we use a method that breaks a string into n elements in length. (If the string length cannot be exactly divided by n, the last element 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:

['Dog', 'dog']
['Love', 'me te', 'nder']
['Jail', 'hous', 'e Ro', 'ck']

+4
source share

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

 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); 
+2
source share

I did not find the answer.

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

+2
source share

All Articles