What will be the output of the following code?string str = "abcdef";cout << str.substr(2, 3);"abc""def""cde""bcd"
Question
What will be the output of the following code?
string str = "abcdef";
cout << str.substr(2, 3);
"abc"
"def"
"cde"
"bcd"
Solution
The output of the code will be "cde".
Here's the step by step explanation:
-
The
substr
function in C++ is used to get a substring from a string. It takes two parameters: the starting index and the length of the substring. -
In the given code,
str.substr(2, 3)
is called. Here, 2 is the starting index and 3 is the length of the substring. -
The string is "abcdef", and the indices start from 0. So, the character at index 2 is 'c'.
-
The length of the substring is 3, so it includes the characters at indices 2, 3, and 4. These characters are 'c', 'd', and 'e', respectively.
-
Therefore, the substring is "cde", and that's what gets printed out.
Similar Questions
What is the output of the following code?string str = "hello";str.insert(1, "123");cout << str;"h123ello""1hello""hello123""h123lo"
What is the output of the following C code?char *ptr;char mystring[] = "abcdefg";ptr = myString;ptr += 5;
What is the output of the following code?char str[] = "hello";int len = strlen(str);printf("%d\n", len);
Find output of the below program:int main(){ char str[]={'e','a','r','t','h'}; printf("%s", str); return 0;}
What will be print after executing following statement int value=65; char ch=value; cout<
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.