read specific chars from a string

Hi, I am writing a code for my assignment.
One of the function needs to read chars from string between '#' and '/' char
e.g:

string name = "London, John # pizza / 10";

I want to read only "pizza" from that string 'name'

Plz help me with this.

thanks in advance.
It's possible using C string functions, I'm not up to speed on basic_string manipulations.

The idea is you find the beginning token and the end, then extract everything in between the two. In this case you'll get the spaces too, but I'm sure you can fix that.

I've not compiled it, so it'll have errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <string>
#include <cstring>

bool Extract(const std::string& name, std::string& ret)
{
    const char *begin = strchr(name.c_str(), '#');
    if (begin == 0)
        return false;
    const char *end = strchr(begin, '/');
    if (end == 0)
        return 0;
    ret = std::string(begin + 1, end - begin);
    return true;
}
Last edited on
using std::strings is better:
1
2
3
string name = "London, John # pizza / 10";
size_t a = name.find('#')+2;// +2 = after '#' and the space following
string result = name.substr ( a, name.find('/')-a );
Topic archived. No new replies allowed.