Click here to Skip to main content
14,665,550 members
Rate this:
Please Sign up or sign in to vote.
See more:
#include <iostream>
#include<string> 

using namespace std;

int main()
{

string s = "abaxyzzyxf" ; 

cout<< s.substr(5,6) ; 

    

    return 0;
}


The above code prints zzyxf and not zz.

What I have tried:

I was writing code to find longest palindrome substring in the given string s and while debugging I came to know that my substr() function is not working properly.

It prints zzyxf and not zz.

Why does this happen ?
Posted
Updated 7-Oct-19 2:12am
Comments
Richard MacCutchan 7-Oct-19 8:41am
   
"Why does this happen ?"
Because you did not check the documentation.
CPallini 7-Oct-19 9:16am
   
:-) Virtual 5.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

string substr (size_t pos = 0, size_t len = npos) const;

The second parameter holds for the length of the substring, not for the index of the end of the capture.
std::string::substr[^]
So, yes, the function is working properly; you just misused its parameters :)
   
v3
Comments
CPallini 7-Oct-19 9:15am
   
5.
phil.o 7-Oct-19 9:50am
   
Thank you Carlo :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100