help understanding npos code

So I am just trying to learn more about strings and I am having trouble with npos, I cant seem to visualize or grasp what its doing, I think I might know but I am unsure, please correct me if im wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>

using namespace std;

int main()
{
    string one, two;

    cin >> one;

    string::size_type pos = one.find(':');

    if(one.npos != pos)
    {
        two = one.substr(pos + 1);
        one = one.substr(0, pos);
    }

    cout << one << endl;
    cout << two << endl;

    return 0;
}


string::size_type pos = one.find(':');

So the .find returns the position it found the character at, in this case ":", and string::size_type pos stores that value in it, correct?

if(one.npos != pos)

and this is saying if the position of the string is not equal to the position of the ":" character, then do the code in the body.

two = one.substr(pos + 1);
one = one.substr(0, pos);

Im a little confused at these though. I think the second line resets the position?
Last edited on
So the .find returns the position it found the character at, in this case ":", and string::size_type pos stores that value in it, correct?

Correct.

if(one.npos != pos)

and this is saying if the position of the string is not equal to the position of the ":" character, then do the code in the body.
If no matches were found, the function returns string::npos.

http://www.cplusplus.com/reference/string/string/find/

 
two = one.substr(pos + 1);

two will store the string created from one, starting from the character after the character that is being looked for, up to the end of one.

 
one = one.substr(0, pos);

This is the second overload for substr(), which will create a string of length pos, starting from index 0 (beginning of the string).
For example,
1
2
3
4
5
6
7
one = "abc:defg"
// string::size_type pos = one.find(':');
-> pos = 3
// two = one.substr(pos + 1);
-> two = "defg"
// one = one.substr(0, pos);
-> one = "abc"

http://www.cplusplus.com/reference/string/string/substr/
Last edited on
Topic archived. No new replies allowed.