Friday, December 8, 2017

JAVA - How to split String to parts

For split String use function java.lang.String.Split(). The parameter is mask for splitting, you can use here advanced regular expressions too.
/* -- split by spaces */

String s = "This is some text";

String[] array = s.split( " " );

System.out.println( s + " -> " + Arrays.toString( array ) );

/* -- split by " is" text */

String[] array1 = s.split( " is" );

System.out.println( s + " -> " + Arrays.toString( array1 ) );

/* -- split by all spaces of any length */

String s2 = "This is some     text";

String[] array2 = s2.split( "\\s+" );

System.out.println( s2 + " -> " + Arrays.toString( array2 ) );

/* -- split groups in () */

String s3 = "(123)(A)(ABDC)";

String[] array3 = s3.split( "[()]" );

System.out.println( s3 + " -> " + Arrays.toString( array3 ) );
Output:
This is some text -> [This, is, some, text]
This is some text -> [This,  some text]
This is some     text -> [This, is, some, text]
(123)(A)(ABDC) -> [, 123, , A, , ABDC]

No comments:

Post a Comment