Jocheved
Jocheved

Reputation: 1135

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.

Upvotes: 5

Views: 3340

Answers (3)

Tunaki
Tunaki

Reputation: 137104

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.

Upvotes: 16

Naman Gala
Naman Gala

Reputation: 4692

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

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

Upvotes: 4

Ravi
Ravi

Reputation: 35569

use limit to split().

String s="abc~def~ghij~klm~nop~qrstu~vwx~hj";
String[] parts = s.split("~",3);
System.out.println(parts[0]);
System.out.println(parts[1]);
System.out.println(parts[2]);

Upvotes: 2

Related Questions