0

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];
    }
  }
}
  • 1
    [`std::string::find_first_of`](https://en.cppreference.com/w/cpp/string/basic_string/find_first_of) should be astoundingly helpful. [Here's a demonstration of it in action](https://stackoverflow.com/a/7621814/4581301) – user4581301 Oct 19 '22 at 22:19
  • Side note: You should state exactly what you want out for the given input. – user4581301 Oct 19 '22 at 22:20
  • for example i have 1+2+3 as user input string, i just want them to split a=1, b = 2,c =3. but i dont know what it can be, maybe it has 6 numbers in one part so i cant substr it – Eduard Atoyan Oct 19 '22 at 22:22
  • Groovy. The demonstration linked above should do almost exactly what you want. I recommend replacing `part1`, `part2` and `part3` with an array or a `vector` like in the demonstration because when you have sequentially named or numbered variables, using a loop and a container is almost always easier (and easier to expand when the teacher says, "Now do it with 4 parts!"). – user4581301 Oct 19 '22 at 22:30
  • @EduardAtoyan If you though outside the box, you could have replaced `+`, `-` and `=` with spaces, and then simply use `std::istringstream` to get the parts. No need for tricky (and error prone) logic finding spaces, etc. – PaulMcKenzie Oct 19 '22 at 22:40
  • Given the string `"2+4x-2x^2=0` what is `part1`, `part2`, etc. supposed to have once done? Is `part2` supposed to have only `4` or `4x`? – PaulMcKenzie Oct 19 '22 at 22:56

2 Answers2

1

Not knowing exactly what you are trying to accomplish, I am assuming you simply want to get the expressions that 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.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45
  • How can i declare every part separately to string, for example part1=2; part2=4x; and so on – Eduard Atoyan Oct 20 '22 at 15:44
  • @EduardAtoyan See: *Note that I use std::vector to store the parts as they are detected.* -- There is nothing more to declare. `parts[0]` is the first part, `parts[1]` is the second part, etc. Look how the output loop is designed -- you don't see 4 separate variables, but instead one variable `parts` that stores all 4 entities. – PaulMcKenzie Oct 20 '22 at 15:46
  • What if it is -2x, how to make it take - with it into string? – Eduard Atoyan Oct 20 '22 at 15:58
  • @EduardAtoyan *What if it is -2x, how to make it take - with it into string?* -- Well, if your goal is to parse this mathematical expression to this extent, then your original approach is ill-advised. It takes much more sophisitication than what you may believe. I was going to comment in the main section that the approach you're taking will only work for certain formatted expressions. If you want something more general, you need to write a formal parser. The answer I gave assumes that all you need to do is use the `-`, `+`, and `=` characters as delimiters. – PaulMcKenzie Oct 20 '22 at 16:07
  • Just to add, the answer given is nothing more than a simpler way of what you were trying to do. In no way should it be used, again, if your intent was to actually use this to solve a mathematical expression or similar. You have to write a parser, i.e. break up the input into tokens, lexical analysis, etc. For example, what if the `^2` term is the first one instead of the last? – PaulMcKenzie Oct 20 '22 at 16:11
  • Its a pity, but i dont know how to do it. im just a starter – Eduard Atoyan Oct 20 '22 at 17:51
  • Yeah, that's the problem with a task like this. On paper it looks easy, and it is easy when a human looks at an algebraic problem. But it gets very sophisticated if you want the computer to mimic equation solving just like a human would. Simple by hand and pencil/paper, difficult to automate by writing a computer program to do the work. Your initial approach is one where most, if not all beginners take, but then realize that it isn't going to work in the long run, and then get blown away by what *will* work. – PaulMcKenzie Oct 20 '22 at 17:53
  • can i take the char before every part except last and check if its minus, so string x="-" + x; and sstream it? – Eduard Atoyan Oct 20 '22 at 18:00
  • @EduardAtoyan -- You are falling into the trap I mentioned. There is a formal way to process strings that represent mathematical equations, and you don't do it by writing ad-hoc techniques to "maybe extract this" or "maybe search for that". Using what you are suggesting, you still will run into a case where it will not work, and to fix it, you risk breaking what was working before. The real way to do this is to write a recursive-descent parser, or use the shunting yard algorithm, or similar. [See this](https://stackoverflow.com/questions/11703082/parsing-math-expression-in-c). – PaulMcKenzie Oct 20 '22 at 18:16
0

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

Retep
  • 1
  • 1