All lessons

7. Strings

Useful string operations

0 of 5 activities0%

Reading 1

Pieces and searches

Open

s.substr(pos, len) returns a piece of the string starting at pos.

s.find(target) returns the index where target starts, or string::npos if it is missing.

cin >> word stops at whitespace. getline(cin, line) reads a whole line including spaces — useful for sentences.

string s = "HelloWorld";
cout << s.substr(0, 5) << endl;  // Hello

if (s.find("World") != string::npos) {
    cout << "found" << endl;
}

Check 2

find miss

Open

If find does not locate the text, it returns

Fill in 3

Slice

Open

The member function that returns a portion of a string is named

Try it 4

substr demo

Open

Change the start and length.

main.cpp
Loading editor…
Output will appear here.

Assignment 5

Contains cpp?

Open

Read one word. If it contains the substring cpp (lowercase), print yes. Otherwise print no.

main.cpp
Loading editor…