Skip to content

Instantly share code, notes, and snippets.

@bmaggi
Last active January 21, 2021 07:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmaggi/2c19155038c510a711923b758084acf8 to your computer and use it in GitHub Desktop.
Save bmaggi/2c19155038c510a711923b758084acf8 to your computer and use it in GitHub Desktop.
Split/Unsplit in Java/Scala
import java.util.Arrays;
class Scratch {
public static void main(String[] args) {
System.out.println(Arrays.equals("a".split("b"),("ab".split("b")))); //true
// but
System.out.println("a".equals(unsplit("a".split("b",-1),"b"))); // true
System.out.println("ab".equals(unsplit("ab".split("b",-1),"b"))); // true
}
public static String unsplit(String[] args,String splitter) {
StringBuilder sb = new StringBuilder();
for (int i = 0;i < args.length-1; i++) {
sb.append(args[i]);
sb.append(splitter);
}
sb.append(args[args.length-1]);
return sb.toString();
}
}
"ab".equals("ab".split("b",-1).mkString("b")) // true
"a".equals("a".split("b",-1).mkString("b")) // true
@UgmaDevelopment
Copy link

Thanks for making this! I found it first and it was going to solve my problem.

For future readers, you can also consider the Java 8 String.join(), as I just found out.

@bmaggi
Copy link
Author

bmaggi commented Jan 21, 2021

Indeed using String.join() is the best option, I don't remember why I did such function
(Maybe the project was in Java 7, join was introduced in Java 8 )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment