Last active
January 21, 2021 07:48
-
-
Save bmaggi/2c19155038c510a711923b758084acf8 to your computer and use it in GitHub Desktop.
Split/Unsplit in Java/Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"ab".equals("ab".split("b",-1).mkString("b")) // true | |
"a".equals("a".split("b",-1).mkString("b")) // true |
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
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.