How to convert an input string into an array in C++?

Viewed 448
myStr = input("Enter something - ")

// say I enter "Hi there" 

arrayStr = myStr.split()
print(arrayStr)

// Output: ['Hi', 'there']

What is the exact C++ equivalent of this code? (My aim is to further iterate over the array and perform comparisons with other arrays).

4 Answers

One way of doing this would be using std::vector and std::istringstream as shown below:

#include <iostream>
#include <string>
#include<sstream>
#include <vector>
int main()
{
    std::string input, temp;
    //take input from user 
    std::getline(std::cin, input);
    
    //create a vector that will hold the individual words
    std::vector<std::string> vectorOfString;
    
    std::istringstream ss(input);
    
    //go word by word 
    while(ss >> temp)
    {
        vectorOfString.emplace_back(temp);
    }
    
    //iterate over all elements of the vector and print them out  
    for(const std::string& element: vectorOfString)
    {
        std::cout<<element<<std::endl;
    }
    return 0;
}

You can use string_views to avoid generating copies of the input string (efficient in memory), it literally will give you views on the words in the string, like this :

#include <iostream>
#include <string_view>
#include <vector>

inline bool is_delimiter(const char c)
{
    // order by frequency in your input for optimal performance
    return (c == ' ') || (c == ',') || (c == '.') || (c == '\n') || (c == '!') || (c == '?');
}

auto split_view(const char* line)
{
    const char* word_start_pos = line;
    const char* p = line;
    std::size_t letter_count{ 0 };
    std::vector<std::string_view> words;

    // while parsing hasn't seen the terminating 0
    while(*p != '\0')
    {
        // if it is a character from a word then start counting the letters in the word
        if (!is_delimiter(*p))
        {
            letter_count++;
        }
        else
        {
            //delimiter reached and word detected
            if (letter_count > 0)
            {
                //add another string view to the characters in the input string
                // this will call the constructor of string_view with arguments const char* and size
                words.emplace_back(word_start_pos, letter_count);

                // skip to the next word
                word_start_pos += letter_count;
            }

            // skip delimiters for as long as you encounter them
            word_start_pos++;
            letter_count = 0ul;
        }

        // move on to the next character
        ++p;
    }

    return words;
}

int main()
{
    auto words = split_view("the quick brown fox is fast. And the lazy dog is asleep!");
    for (const auto& word : words)
    {
        std::cout << word << "\n";
    }

    return 0;
}
#include <string>
#include <sstream>
#include <vector>
#include <iterator>

template <typename Out>
void split(const std::string &s, char delim, Out result) {
    std::istringstream iss(s);
    std::string item;
    while (std::getline(iss, item, delim)) {
        *result++ = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}

std::vector<std::string> x = split("one:two::three", ':');

Where 'x' is your converted array with 4 elements.

Basically @AnoopRana's solution but using STL algorithms and removing punctuation signs from words:

[Demo]

#include <cctype>  // ispunct
#include <algorithm>  // copy, transform
#include <iostream>  // cout
#include <iterator>  // istream_iterator, ostream_iterator
#include <sstream>  // istringstream
#include <string>
#include <vector>

int main() {
    const std::string s{"In the beginning, there was simply the event and its consequences."};
    std::vector<std::string> ws{};
    std::istringstream iss{s};
    std::transform(std::istream_iterator<std::string>{iss}, {},
        std::back_inserter(ws), [](std::string w) {
            w.erase(std::remove_if(std::begin(w), std::end(w),
                        [](unsigned char c) { return std::ispunct(c); }),
                    std::end(w));
            return w;
    });
    std::copy(std::cbegin(ws), std::cend(ws), std::ostream_iterator<std::string>{std::cout, "\n"});
}

// Outputs:
//
//   In
//   the
//   beginning
//   there
//   was
//   simply
//   the
//   event
//   and
//   its
//   consequences
Related