CodingHowTo

One Function to Split Strings by Any Delimiter

One Function to Split Strings by Any Delimiter

Effortlessly split a string into parts using any delimiter with this simple one-function solution in C++.

Step-by-Step Guide


#include <iostream>
#include <vector>
#include <string>

std::vector<std::string> splitString(const std::string& str, char delimiter) {
    std::vector<std::string> result;
    std::string currentPart;
    for (char ch : str) {
        if (ch == delimiter) {
            if (!currentPart.empty()) {
                result.push_back(currentPart);
                currentPart.clear();
            }
        } else {
            currentPart += ch;
        }
    }
    if (!currentPart.empty()) {
        result.push_back(currentPart);
    }
    return result;
}

    

Usage Example

Here’s how you can use the `splitString` function:


int main() {
    std::string input = "Hello,World,this,is,a,test";
    char delimiter = ',';
    std::vector<std::string> parts = splitString(input, delimiter);

    for (const std::string& part : parts) {
        std::cout << part << std::endl;
    }

    return 0;
}

    

Conclusion

Having a single function to split strings by any delimiter is invaluable for handling various text processing tasks. This C++ function provides a flexible and efficient way to achieve this, making your code cleaner and more maintainable. By using this solution, you can easily split strings based on different delimiters as needed.