C library strcspn in C++ (legacy headers): for the given strings, what index does strcspn("India", "CuriousTab") return?\n\n#include<iostream.h>\n#include<string.h>\nclass CuriousTab\n{\n int val;\npublic:\n void SetValue(char str1, char str2)\n {\n val = strcspn(str1, str2);\n }\n void ShowValue()\n {\n cout << val;\n }\n};\nint main()\n{\n CuriousTab objCuriousTab;\n objCuriousTab.SetValue((char)"India", (char)"CuriousTab");\n objCuriousTab.ShowValue();\n return 0;\n}

Difficulty: Easy

Correct Answer: 3

Explanation:


Introduction / Context:
strcspn returns the length of the initial segment of the first string that consists of characters not found in the second string. Once a character from the second string appears in the first string, the count stops, and that index is returned.


Given Data / Assumptions:

  • First string: "India".
  • Second string: "CuriousTab" (case-sensitive).
  • We compute strcspn("India", "CuriousTab").


Concept / Approach:
Scan "India" left to right until a character appears that is present in "CuriousTab". The function returns the count of characters before that first match.


Step-by-Step Solution:
Check characters in order: I (uppercase) not in "CuriousTab".n not in the second string.d not in the second string.i (lowercase) is in "CuriousTab".Therefore the initial non-matching span length is 3, so the function returns 3.


Verification / Alternative check:
Print strcspn outputs for intermediate prefixes to confirm behavior; also note the function is case-sensitive.


Why Other Options Are Wrong:
2 stops too early; 5 or 8 ignore the early match; returning -1 is not how strcspn signals matches.


Common Pitfalls:
Confusing strcspn with strspn, or forgetting its case sensitivity.


Final Answer:
3

More Questions from Objects and Classes

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion