Home > Net >  parsing a string when there are two delimiters
parsing a string when there are two delimiters

Time:07-11

Parsing the given string to be able to construct a graph . I have been given this string

string str ="abc,def,0.9;ghi,jkl,109;mno,par,155";

I need to parse this string such that i can construct an edge between abc and def, ghi and jkl, mno and pqr with weights 0.9, 109, 155.

I am stuck only in parsing part .

stringstream ss(str);
    for(int i =0 ;i<str.size();i  ){
         string substr;
        getline(ss, substr, ',');
       
        cout <<substr<<endl;
    }

But this gives 0.9;ghi on one line.

Any suggestions will be highly appreciated.

CodePudding user response:

There is probably a library that can do this too. Here is an approach that uses a vector of string_view

#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <set>

auto get_substring_views(const std::string& input, const std::set<char>&& delimiters)
{
    std::vector<std::string_view> views;

    auto begin_of_word = input.begin();
    auto end_of_word = begin_of_word;

    while (end_of_word != input.end())
    {
        // check if input character can be found in delimiter
        while (end_of_word != input.end() && (delimiters.find(*end_of_word) == delimiters.end()))   end_of_word;

        // double delimiter will result in empty view being added (should be fine)
        views.emplace_back(begin_of_word, end_of_word);

        // next word starts one after delimiter
        if ( end_of_word != input.end() ) begin_of_word =   end_of_word;
    }

    return views;
}

int main()
{
    std::string input{ "abc,def,0.9;ghi,jkl,109;mno,par,155" };

    // note will return views on input so input must stay in scope
    auto substrings = get_substring_views(input, { ',',';' });

    for (const auto& substring : substrings)
    {
        std::cout << substring << "\n";
    }

    return 0;
}

CodePudding user response:

You can use just one more string stream as for example

#include <iostream>
#include <sstream>
#include <string>

int main()
{
    std::string str ="abc,def,0.9;ghi,jkl,109;mno,par,155";

    std::istringstream iss1( str );
    std::string line;

    while ( std::getline( iss1, line, ';' ) )
    {
        std::istringstream iss2( line );
        std::string item;
        while ( std::getline( iss2, item, ',' ) )
        {
            std::cout << item << ' ';
        }
        std::cout << '\n';
    }
}

The program output is

abc def 0.9 
ghi jkl 109 
mno par 155 

To get double values you can use standard function std:stod.

  •  Tags:  
  • c
  • Related