1

I want to split a string at a certain point, but keep the character I'm splitting it at. For example:

Input:
a:b

Output:
a
:
b

Is there anyway I can use this with Java's split() method? Thanks :)

chapman
  • 859
  • 3
  • 9
  • 16

3 Answers3

1

You can use StringTokenizer class in Java.

StringTokenizer stk = new StringTokenizer(inputStr,":", true);

This will return tokens as well as delimiter.

Arjit
  • 3,290
  • 1
  • 17
  • 18
0

Quick solution from my mind

  1. First split it from the character you want to split
  2. Join it with another string like this ____:____
  3. Now, split again with ____

____ is just a string which I am sure doesn't exist in the string. You can use anyother substring as well depending upon your use case

Order of time complexity O(3*N)

For Example

Your string is a:b.

  1. Split it with :

    String Array you get is ["a", "b"]

  2. Join with ____:____

    String you get is a_:_b

  3. Split again with ____

    You get ["a", ":", "b"] (desired output)

Just giving an idea.

Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
0
Scanner  = new Scanner(System.in);
String input = s.next();
for (String str : input.split()) {
  System.out.println(str);
  System.out.println(":");
}
Ypnypn
  • 933
  • 1
  • 8
  • 21