LearnFrenzy
Sign in Take a free test

std::string · Predict the Output · Question 2

find, rfind and checking npos Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 2 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>
#include <string>

int main() {
    std::string s = "banana";
    std::cout << s.find('a') << ' ' << s.rfind('a') << ' ' << s.find("na") << ' '
              << s.find("na", 3) << ' ' << (s.find('z') == std::string::npos) << '\n';
    return 0;
}
  • A 1 5 2 4 1 Correct
  • B 1 5 2 2 1
  • C 0 5 2 4 1
  • D 1 5 3 4 0
Correct Answer: Option A

b-a-n-a-n-a: first a at 1, last at 5, "na" first at 2; searching from 3 finds the next "na" at 4. A missing character gives npos.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links