Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string only two times

I have a string like abc~def~ghij~klm~nop~qrstu~vwx~hj. I want to split it only two times (to three parts as the result): that means wherever I get ~ symbol I need to split abc, def and third as a single string only ghij~klm~nop~qrstu~vwx~hj.

I know how to split into strings wherever ~ symbol comes

String[] parts = stat.split("~");
String part1 = parts[0];
String part2 = parts[1];
String part3 = parts[2];

Here I get only part3 as ghij, I need the whole string remaining long with ~ symbol.

like image 201
Jocheved Avatar asked Nov 30 '22 10:11

Jocheved


2 Answers

You can use String.split(String regex, int limit).

String[] parts = stat.split("~", 3);
like image 41
Naman Gala Avatar answered Dec 04 '22 15:12

Naman Gala


This splits the stat String only two times, i.e. it splits it in 3 parts:

String[] parts = stat.split("~", 3);

String.split(String regex, int limit) method allows for control over the number of resulting parts.

Quoting the Javadoc:

The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter.

like image 159
Tunaki Avatar answered Dec 04 '22 15:12

Tunaki