Home > OS >  How to split string into multiple strings by delimiter
How to split string into multiple strings by delimiter

Time:10-20

I tried to split string into 3 parts but its not working properly. i need it to be split by and - and =.

int main() {

double a, b, c, x, x1, x2, d;

string str, part1, part2, part3, avand, miand, azand;

str = "2 4x-2x^2=0";
size_t count = count_if(str.begin(), str.end(), [](char c) {return c == 'x'; });

if (count == 2) {
    int i = 0;
    while (str[i] != ' ' && str[i] != '-') {
        part1 = part1   str[i];
        i  ;
    }
    while (str[i] != ' ' && str[i] != '=') {
        part2 = part2   str[i];
        i  ;
    }
    i  ;
    for (i; i < str.length(); i  ) {
        part3 = part3   str[i];
    }
  }
}

CodePudding user response:

You need to add a i ; after the first while loop to pass the ' ', other wise the code won't enter the second while loop.

Also try to use stringstream to parse the sentence for general purpose. How to use stringstream to separate comma separated strings

CodePudding user response:

Not knowing exactly what you are trying to accomplish, I am assuming you simply want to get the expressions fall between the , - and the =.

If so, since the characters you want to split the string on are , - and =, another solution is to replace those characters with a single delimiter (a space for example), and then use std::istringstream to get the parts of the string that are remaining:

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

int main() 
{
   std::string str = "2 4x-2x^2=0";
   std::vector<std::string> parts;

   // replace the delimiters with spaces 
   for ( auto& ch : str)
   {
       if ( ch == ' ' || ch == '-' || ch == '=')
          ch = ' ';
   }

   // use std::istringstream to parse the new string
   std::istringstream strm(str);
   std::string part;
   while (strm >> part)
      parts.push_back(part);

    // Output values
    for (auto& s : parts)
       std::cout << s << "\n";
}

Output:

2
4x
2x^2
0

Note that I use std::vector to store the parts as they are detected.

  • Related