Reputation: 11
Hi guys I'm new to programming and I'm currently working on an assignment for my java class that states this
The split method in the String class return 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 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 Strings
output
[ab, #, 12, #, 453]
and this is my code
public class Assignment {
public static void main(String[] args) {
String str= "ab#12#453";
String []temp;
String delimiter= "#";
temp=str.split(delimiter);
for(int i = 0;i<temp.length;i++)
{
if(i == 0){
System.out.printf("[");
}
System.out.printf(temp[i]);
if(i != temp.length - 1){
System.out.printf(", " + delimiter + ", ");
}
if(i == temp.length - 1){
System.out.printf("]");
}
}
}
}
As you can see, I'll get the correct output, but I'm pretty sure it's not how the assignment is asking. Could someone point out where I might have gone wrong here and where to begin thinking in the correct way?
Upvotes: 1
Views: 1757
Reputation: 105
Since you don't have any specific instructions, you could just throw in a # as every other element of the array.
Keep in mind you would have to extend the array by array.length()/2
.
A pointless solution, but simple.
Upvotes: 0
Reputation: 541
You are asked to
Implement the following new method that returns an array of strings split by the matching delimiters, including the matching delimiters.
public static String[] split(String s, String regex)
which returns a string array (String[]
) and takes two strings (the one to split and the delimiter as regular expression) as arguments when called.
So, actually you are asked to implement the method split
like this:
public static String[] split(String s, String regex) {
/*
split your input string 's' by the delimiter 'regex',
add each sub string to an array
and return the generated array
*/
}
The method split
can then be called, as shown in the problem statement.
I also suggest you have a look at Java regular expressions
Upvotes: 1