3

I need to split a string into pairs of characters, but where the pairs overlap. For example, I have a string Testing, and I want the output:

[Te, es, st, ti, in, ng]

I tried some things with String.split but I am not getting the right output:

String s = "Testing";
System.out.println(java.util.Arrays.toString(s.split("(?<=\\G..)")));

That gives me:

[Te, st, in, g]

Can anyone help me?

Boann
  • 48,794
  • 16
  • 117
  • 146
Sanket990
  • 665
  • 1
  • 10
  • 22

3 Answers3

5

String#split method simply searches for places to split, it can't add anything new to result. In other words you can't split like

"abc"` -> ["ab", "bc"]

because b can appear in only one element in resulting array.

What you can do is use Pattern/Matcher, specifically Matcher#find() method and consume one character at a time, while "peeking" at next character without consuming it. The "peeking" part can be achieved with look-around mechanism because it is zero-length technique.

Demo:

Pattern p = Pattern.compile(".(?=(.))");
Matcher m = p.matcher(yourString);
while(m.find()){
    System.out.println(m.group() + m.group(1));
}

Alternatively you can also use String#substring(start, end)

String data = "Testing";
for (int i=0; i<data.length()-1; i++){
    System.out.println(data.substring(i,i+2));
}

or using String#charAt(index)

String data = "Testing";
for (int i = 0; i < data.length() - 1;i++) {
    System.out.append(data.charAt(i)).println(data.charAt(i+1));
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • Thanks Pshemo for giving to me solution – Sanket990 Jul 03 '15 at 19:50
  • @Sanket990 I was hoping more for giving you explanation rather than solution. If some part of my answer is not clear feel free to ask about it. Otherwise my answer may be kind of pointless for you. – Pshemo Jul 03 '15 at 19:54
  • I am running your logic code and my criteria wise this answer is full filled i am already upvotted your answer .tnx – Sanket990 Jul 03 '15 at 20:05
  • It is not that I am concern about upvotes. It is more like I would rather know if you are able to easily understand my answer. If there is something unclear feel free to ask. – Pshemo Jul 03 '15 at 20:16
  • ya ya i got your logic and i am easily understand thanks. – Sanket990 Jul 03 '15 at 20:19
2

As @pshemo's answer said, a split consumes input, so you can't get a given character from the input in two parts of the split.

However, here a one-line solution that gets the job done:

Arrays.stream(s.split("")).reduce((a, b) -> {System.out.println(a + b); return b;});
Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

It would be quicker, theoretically, to just use a for-loop.

List<String> split(String string) {
    List<String> split = new ArrayList<>();
    for (int index = 0; index < string.length() - 1; index++)
        split.add(string.substring(index, index + 2));
    return split;
}

Output

[Te, es, st, ti, in, ng]
Reilas
  • 3,297
  • 2
  • 4
  • 17