I am trying to write a simple program that takes two user inputs: a String to be split, and a String that specifies one or more delimiters. The program should print an array of strings consisting of the substrings split AND the delimiters. I must implement the public static String[] split(String s, String regex)
If the String to be split is
cd#34#abef#1256
My current code correctly outputs
[cd, 34, abef, 1256]
What I need outputted is
[cd, #, 34, abef, #, 1256]
And what if the String to be split has two user-specified delimiters
cd?34?abef#1256
How can I split that so it looks like
[cd, ?, 34, ?, abef, #, 1256]
None of the previous questions I've looked into used user-specified Strings and delimiters.
Here's my current code:
import java.util.Arrays;
import java.util.Scanner;
public class StringSplit
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scan.next();
System.out.print("Specify delimiter(s): ");
String del = scan.next();
String[] result = split(str, del);
System.out.print(Arrays.toString(result));
}
public static String[] split(String s, String regex)
{
String[] myString = s.split(regex);
return myString;
}
}