-3

So i have a text file that contains information about books (title,author,genre) on every line that would look like this '[title]' '[author]' '[genre]'. How could i divide this line in 3 different strings so that each one is the title/author/genre?

  • 4
    Possible duplicate of [Parse (split) a string in C++ using string delimiter (standard C++)](http://stackoverflow.com/questions/14265581/parse-split-a-string-in-c-using-string-delimiter-standard-c) – Brandon McKenzie May 16 '17 at 14:51
  • you may use regex also, which is supported in standard C++ library. strtok from answer below aworks only with C strings and only with ANSI. if you want to experiment with regexs, there is online editor that helps to learn it: https://regex101.com/ – Swift - Friday Pie May 16 '17 at 15:20
  • The strings are surrounded by ', yes? A line would look like `'20,000 Leagues Under the Sea' 'Jules Verne' 'science fiction'`, correct? – user4581301 May 16 '17 at 15:23
  • yes thats how they would look like. Also it would be helpful if there is a solution without vectors. – Kliment Berbatov May 16 '17 at 15:55
  • 1
    @Kliment Berbatov you can replace vector by any container you should use of naked pointers or just copy them into structure. it depends on what software architecture you use. Example just cleaner when not in raw C code. is that an education project, who would use such limitation? – Swift - Friday Pie May 16 '17 at 15:59

1 Answers1

0

You can split string according ANY rule if you can define regexp for that rule , then use sregex_token_iterator to enumerate all matches in string. This example would save all matches into a vector.

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

std::vector<std::string> get_params(const std::string& sentence) 
{
   std::regex reg("([^\']*)");

   std::vector<std::string> names(
       std::sregex_token_iterator(sentence.begin(), sentence.end(), reg),
       std::sregex_token_iterator());
   return names;
}

int main()
{
    std::string str = "\'String1\' \'String2\' \'String3\'";
    std::vector<std::string> v = get_params(str);

    for (auto const& s : v)
            std::cout << s << '\n';
}
Swift - Friday Pie
  • 8,633
  • 1
  • 16
  • 31