Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
1.00/5 (1 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

C++
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 :)
 
Share this answer
 
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)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900