-9

How to split a word to 2 words example like

 String a="pavanpavan"

and to print this in 2 variables like

a1="pavan"
a2="pavan"

I've tried to split using the split("p"), but the output will be

avan
avan

How to print full word as pavan and pavan?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • How about taking first half substring and second half of the substring ? – 11thdimension Aug 12 '16 at 14:14
  • 8
    What is the actual rule you want to split on? Are you actually just looking for the literal string "pavenpaven", or is there a more general rule of which this is an example? – azurefrog Aug 12 '16 at 14:14

3 Answers3

2

A workaround for simply doing this would be.

a1 = a.substring(0,a.length()/2);

a2 = a.substring(a.length()/2);
Javant
  • 1,009
  • 10
  • 17
1

You have two ways: first one is to use .substring()

String a ="pavanpavan";
String a1 = a.substring(0, 5);
String a2 = a.substring(5);

And the second using .split() and regex

String a="pavanpavan";
String[] array = a.split("(?=p)");
String a1 = array[0];
String a2 = array[1];

Source: How to split String with some separator but without removing that separator in Java?

Community
  • 1
  • 1
Paolo Forgia
  • 6,572
  • 8
  • 46
  • 58
0
int i = a.lastIndexOf("pavan");
if (i != -1) {
    String b = a.substring(i); //pavan
    String c = a.substring(0, i); //pavan
}
Jaroslaw Pawlak
  • 5,538
  • 7
  • 30
  • 57
SomeDude
  • 13,876
  • 5
  • 21
  • 44