Code Logo

Split and Join with String methods

Published at25 Jul 2026
Java OOP Easy 0 views
Like0

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

Example 1
Input
"one,two,three"
Output
one-two-three
Explanation

Words with hyphen join

Example 2
Input
"a,b,c"
Output
a-b-c
Explanation

Split by comma, join with hyphen

Example 3
Input
"hello"
Output
hello
Explanation

No delimiter, unchanged

Example 4
Input
"a,,c"
Output
a--c
Explanation

Empty element preserved

Example 5
Input
"x,y,z"
Output
x-y-z
Explanation

Three letters

Algorithm Flow

Recommendation Algorithm Flow for Split and Join with String methods
Recommendation Algorithm Flow for Split and Join with String methods

Solution Approach

class Solution {
    public String solution(String s) {
        String[] parts = s.split(",");
        return String.join("-", parts);
    }
}

Best Answers

java - Approach 1
class Solution {
    public String solution(String s) {
        String[] parts = s.split(",");
        return String.join("-", parts);
    }
}