0

Possible Duplicate:
C++ string.substr() function problem

string s = "0123456789";

cout<<s.substr(0,4)<<endl;

cout<<s.substr(4,7)<<endl;

The output of the above lines of code was pretty unexpected , s.substr(0,4) gave me "0123", s.substr(4,7) gave me "456789" . It was expecting only "456" . Am I missing something here , and is there any alternative to substr function in C++ , which would give me only "456" on the second call.

Community
  • 1
  • 1
motiur
  • 1,640
  • 9
  • 33
  • 61
  • This is definitely a dupe, but I can't find it. – John Dibling Oct 22 '12 at 14:45
  • @JohnDibling This one is the exact same issue: http://stackoverflow.com/questions/2477850/c-string-substr-function-problem I'll vote to close as duplicate. – jogojapan Oct 22 '12 at 14:46
  • @jogojapan: That's not the one I was thinking of, but it will do. – John Dibling Oct 22 '12 at 14:48
  • @jogojapan: I got my answer anyway . So thanks. – motiur Oct 22 '12 at 14:49
  • @JohnDibling: No offense , the problem was so simple , nobody would want to look at the complicated example jogojapan suggested . So , I would request for the example to stay here , the usage of substr() function is not obvious to all at first glance . – motiur Oct 22 '12 at 14:55
  • @MotiurRahman: The dupe I was trying to remember was an *exact* duplicate of the posted question. And, no offense, but the use of `substr` is quite obvious if you read the documentation and not try to guess. – John Dibling Oct 22 '12 at 14:58
  • http://en.cppreference.com/w/cpp/string/basic_string/substr – John Dibling Oct 22 '12 at 14:59
  • @JohnDibling: Okay , well flag it then . – motiur Oct 22 '12 at 15:04
  • I voted to close as a dupe already. Flagging for moderator attention isn't really called for in this case, I don't think. – John Dibling Oct 22 '12 at 15:10

3 Answers3

5

The second argument of substr is the length of the desired substring, not the end index. So instead of s.substr(4,7), you want s.substr(4,3).

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
2

substr takes the initial position and the desired length - see here.

Try substr(4,3).

Chowlett
  • 45,935
  • 20
  • 116
  • 150
2

The 2nd parameter of substr is the count of symbols, not the end index as you assume. You shall use substr(4,3).

Andriy
  • 8,486
  • 3
  • 27
  • 51