How to split String with multiple Separator at run time

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to split String with multiple Separator at run time



I need to write a Java code which can split required String based on the Separator that we will pass. The number of separator can change too.
Example:


new StringSplit(".").split("foo.bar#baz")
output = foo, bar#baz
new StringSplit(".", "#").split("foo.bar#baz")
output = foo, bar, baz



In constructor i am handle the number separator, but i am facing problem while designing the split method. Please help me on the same.





Could you post sample input and expected output?
– Andrei Suvorkov
Aug 10 at 14:32





What is StringSplit!
– YCF_L
Aug 10 at 14:32



StringSplit





@BishnuPrasad How is this question related to Selenium? Am I missing something?
– New contributor
Aug 11 at 7:59



Selenium




1 Answer
1



Ok, If I can understand your logic you need something like this :


public static String split(String input, String... delimiters)
String regex = Arrays.toString(delimiters).replace(", ", "");
return input.split(regex);



You can call your method like so :


String input = "foo.bar#baz";
String result = split(input, "\.", "#");



Outputs


[foo, bar, baz]



Details :



This method will take the string you want to split and the varargs of delimiters.

the String::split method in Java use regex so you can create a regex by the delimiters I Just use a simple trick which is Arrays.toString(delimiters) this will return the string format of an varargs for example [., #] the just replace the , to get a class of delimiters [.#]


String::split


Arrays.toString(delimiters)


[., #]


,


[.#]





Hey...The above solution works fine...but how i can split if the separator it self a comma. For example, String input = "foo.bar#baz,eat" and split(input, "\.", "#", "\,") 3rd separator is comma(,)
– Bishnu Prasad
Aug 11 at 9:05






@Bishnu Prasad the comma in java is not special character so dont escape it like you do with the dot just use split(input, "\.", "#", ",")
– YCF_L
Aug 11 at 10:23







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard