Split Strings by Separator
Problem
You are given an array of strings words and a character separator. Split each string in words by separator and return a single array of all the resulting pieces, in order, excluding any empty strings.
words = ["one.two.three","four.five"], separator = "."["one","two","three","four","five"]def split_words_by_separator(words, separator):
result = []
for w in words:
for part in w.split(separator):
if part != "":
result.append(part)
return result
function splitWordsBySeparator(words, separator) {
const result = [];
for (const w of words) {
for (const part of w.split(separator)) {
if (part !== "") {
result.push(part);
}
}
}
return result;
}
class Solution {
public List<String> splitWordsBySeparator(List<String> words, char separator) {
List<String> result = new ArrayList<>();
for (String w : words) {
for (String part : w.split(java.util.regex.Pattern.quote(String.valueOf(separator)))) {
if (!part.isEmpty()) {
result.add(part);
}
}
}
return result;
}
}
vector<string> splitWordsBySeparator(vector<string>& words, char separator) {
vector<string> result;
for (const string& w : words) {
string cur = "";
for (char c : w) {
if (c == separator) {
if (!cur.empty()) result.push_back(cur);
cur = "";
} else cur += c;
}
if (!cur.empty()) result.push_back(cur);
}
return result;
}
Explanation
We need to chop every word at the separator and gather the leftover chunks into one flat list. The two things to be careful about are: keep the pieces in order, and throw away any empty piece (which appears when the separator is at the start, the end, or doubled up).
The structure is two nested loops. The outer loop walks each word; the inner loop walks the substrings produced by splitting that word on separator.
For each piece we check part != "". Only non-empty pieces are appended to result; empty ones are silently skipped. This single guard handles all the tricky edge cases — leading/trailing separators and consecutive separators all just produce empties that we discard.
Languages with a built-in split make the inner loop trivial; in C++ we build each piece manually by accumulating characters and flushing the buffer whenever we hit a separator (and once more at the end).
Example: words = ["one.two.three","four.five"], separator = '.'. The first word yields "one","two","three" and the second yields "four","five", so the combined answer is ["one","two","three","four","five"].