lundi 19 octobre 2020

How substr() of c++ really works?

I'm trying to print the substring of a string but the substr() function's behaviour seems odd to me.

In my below program, I'm trying to print the substring of a string with value "Kamal".

Here, substr(0,4) prints "Kama" which makes me assume that 0 is inclusive and 4 is exclusive. But substr(1,4) prints "amal" which violates my above understanding since the character in position 4 is printed while in previous case it's not. Can you explain this strange behaviour.

If this question is really dumb, sry this is the first time I'm using substr(). I've searched the net but can't seem to find any answer useful.

#include<iostream>
#include<string>
using namespace std;

int main() {
    string s1 = "Kamal";

    cout << s1.substr(0, 4) << '\n';
    cout << s1.substr(1, 4) << '\n';

    return 0;
}

Output: enter image description here

Aucun commentaire:

Enregistrer un commentaire