How to join a vector of strings into a string in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <string>
 
std::string join_a_vector_of_strings_into_a_string(std::vector<std::string> vec) {
    std::string str = "";
    
    for (size_t i = 0; i < vec.size(); ++i) {
        str += vec[i];
        if (i < vec.size() - 1) {
            str += "-";
        }
    }
    
    return str;
}
    
int main() {
    std::vector<std::string> vec = {"python", "java", "c", "c++", "c#"};
     
    std::string str = join_a_vector_of_strings_into_a_string(vec);
     
    std::cout << str << std::endl;
}

    
/*
run:
    
python-java-c-c++-c#
    
*/

 



answered Aug 26, 2024 by avibootz
edited Aug 26, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <sstream>

std::string joinStrings(const std::vector<std::string>& strings, const std::string& delimiter) {
    std::ostringstream oss;
    
    for (size_t i = 0; i < strings.size(); i++) {
        if (i != 0) {
            oss << delimiter;
        }
        oss << strings[i];
    }
    
    return oss.str();
}

int main() {
    std::vector<std::string> words = {"c", "c++", "java", "python"};
    std::string delimiter = " ";
    
    std::string result = joinStrings(words, delimiter);
    
    std::cout << result << std::endl;  
}



/*
run:

c c++ java python

*/

 



answered May 4, 2025 by avibootz

Related questions

...