In: Computer Science
The split method in the String class returns an array of strings
consisting of the substrings split by the delimiters. However, the
delimiters are not returned. Implement the following new method
that returns an array of strings consisting of the substrings split
by the matching delimiters, including the matching
delimiters.
public static String[] split(String s, String regex)
For example, split("ab#12#453", "#") returns ab, #, 12, #, 453 in
an array of String, and split("a?b?gf#e", "[?#]") returns a, ?, b,
?, gf, #, and e in an array of String.
Write a test program to show that your split method works
properly.
PLEASE DO THE QUESTION IN A SIMPLER WAY
Please find the answer below.
Please do comments in case of any issue. Also, don't forget to rate
the question. Thank You So Much.
SubstringOperator.java
package c15;
import java.util.Arrays;
public class SubstringOperator {
public static String[] split(String s, String
regex) {
int count=0;
for(int i=0;i<s.length();i++)
{
if(regex.indexOf(s.charAt(i))!=-1) {
count++;
}
}
int size = count*2+1;
String res[] = new
String[size];
String tmp;
int storeCount=0;
for(int i=0;i<s.length();i++)
{
int
index=regex.indexOf(s.charAt(i));
if(index!=-1)
{
tmp = s.substring(0,i);
res[storeCount] = tmp;
storeCount++;
res[storeCount] = s.charAt(i)+"";
s = s.substring(i+1);
storeCount++;
i=0;
}
}
res[storeCount] = s;
return res;
}
public static void main(String[] args) {
String res[] = split("a?b?gf#e",
"[?#]");
System.out.println(Arrays.toString(res));
String res2[]=split("ab#12#453",
"#");
System.out.println(Arrays.toString(res2));
}
}
output