0

I have been trying to get substrings in a XML tag. The string: "<Fruits Type="Apple" Quantity="10"></Fruits>",

I want only substring1 = Apple substring2 = 10.

string string1 ="<Fruits Type="Apple" Quantity="10"></Fruits>";
 int lPos = string1 .find("\"");
 string substring2 = string1.substr(lPos + 1);
 string substring1 = substring2.substr(0, substring2.find("\""));
 substring2 = substring2.substr(substring2.find("\""), substring2.rfind("\"")- substring2.find("\""));
 substring2 = substring2.substr(substring2.rfind("\"")+1);
 cout<<substring1 << "\n" << substring2;

The Thing is I'm able to get expected output. But what I want is to know if there is any efficient way other than this method.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
CodeKhaleesi
  • 79
  • 1
  • 1
  • 8

1 Answers1

0

Ok,

First of all there is no code provided by you, so there is no way what is wrong with it.

Second, in your string1 variable there is an error, it should be:

string string1 ="<Fruits Type=\"Apple\" Quantity=\"10\"></Fruits>";

or it will not compile.

Third, if you really want to search for strings like that, it can be done like this:

#include <iostream>
#include <string>

static std::string input = "<Fruits Type=\"Apple\" Quantity=\"10\"></Fruits>";

int main()
{
    std::string::size_type begin = input.find('\"');
    std::string::size_type end   = input.find('\"', ++begin);

    std::string buffer(input, begin, (end - begin));
    std::cout << buffer << std::endl;
    return 0;
}

Fourth and most important - please be kind to yourself and use some XML library to do it for you. You may face long, sleepless nights otherwise...

Diodacus
  • 663
  • 3
  • 8