Quick and Clean: Join a Vector of Strings with a Separator
Quick and Clean: Join a Vector of Strings with a Separator
Content
Let's say you have a vector of strings, and you want to join them into a single string with a separator like a comma or space. Here’s how you can do it:
#include <iostream>
#include <vector>
#include <string>
std::string joinStrings(const std::vector<std::string>& strings, const std::string& separator) {
std::string result;
for (size_t i = 0; i < strings.size(); ++i) {
if (i != 0) {
result += separator;
}
result += strings[i];
}
return result;
}
int main() {
std::vector<std::string> words = {"Hello", "world", "this", "is", "C++"};
std::string joinedString = joinStrings(words, ", ");
std::cout << joinedString << std::endl;
return 0;
}
In this code:
- We define a function `joinStrings` that takes a vector of strings and a separator string as parameters.
- We iterate through the vector, appending each string to the result with the specified separator.
- The `main` function demonstrates how to use this function by joining a vector of words into a single string separated by commas and spaces.
Conclusion
Joining a vector of strings with a separator is a straightforward task in C++. By using the code provided, you can efficiently concatenate multiple strings into one, making your code cleaner and more maintainable. This method is particularly useful for generating comma-separated values (CSV) or creating formatted output.