Split and Join with String methods
Write a Java function that takes a comma-separated string, splits it into parts using split(), and rejoins them with hyphens using String.join(). For example, "a,b,c" becomes "a-b-c".
String.split(String regex) divides a string into an array of substrings based on matches of the given regular expression. It is a powerful method for parsing structured text like CSV data. String.join(CharSequence delimiter, CharSequence... elements) joins multiple string elements with a delimiter, added in Java 8.
The split() method takes a regex as its argument. For splitting on commas, use split(","). It returns a String[]. The join() method is the inverse operation — it takes a delimiter and an array/varargs of elements and concatenates them with the delimiter between each element.
Time complexity is O(n) where n is the string length for both split and join. Split uses regex pattern matching internally, and join uses StringBuilder for efficient concatenation. Both methods create new String objects.
Edge cases include empty strings (split returns array with empty string), strings with no delimiter (returns single-element array), leading/trailing delimiters (empty elements adjacent to delimiters), and multiple consecutive delimiters (also produce empty elements).
Example Input & Output
Words with hyphen join
Split by comma, join with hyphen
No delimiter, unchanged
Empty element preserved
Three letters
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public String solution(String s) {
String[] parts = s.split(",");
return String.join("-", parts);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
