-2

The code below:

String str = "She is a girl";
String[] substr = str.split("is");

The output for substr[1] is "a girl". But my expected is the output "is a girl". How can I solve this? Can I split the string based on the index of token?

thomasfuchs
  • 5,386
  • 2
  • 18
  • 38
latala
  • 17
  • 3

4 Answers4

4

Use a positive lookahead token.

String[] substr = str.split("(?=is)");
Codebender
  • 14,221
  • 7
  • 48
  • 85
3

str.substring(str.indexOf("is"))

If you want to get the first part of the string, you may call str.substring(0, str.indexOf("is"))

Edit: check out the answer by @Codebender It's more apt for this question.

Harsh Poddar
  • 2,394
  • 18
  • 17
0

As split method excludes the token, the output of you program is correct. For your need instead of split , you can use substring and index as below

String str = "She is a girl";
String substr1 = str.substring(str.indexOf("is"), str.length);

Prefer substring if you need to get one part of string. Split is good when you need to break string into multiple strings based on token.

If you want to use split only or have multiple tokens and want to include token also, you can use look ahead token

Community
  • 1
  • 1
Panther
  • 3,312
  • 9
  • 27
  • 50
0

You may use replaceFirst

string.replaceFirst(".*?\\b(is)\\b", $1);

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274