Menu
Coddy logo textTech

String Functions Part 2

Part of the Fundamentals section of Coddy's C++ journey — lesson 71 of 74.

Here are more useful functions for strings:

  • erase(pos, len): Removes len characters starting at position pos from the current string.
  • find(str): Returns the position of the first occurrence of str in the current string. Returns some object that can be compared to -1 if not found.
  • clear(): Removes all characters from the string, making it empty.
  • empty(): Returns true if the string is empty, false otherwise.

For example using the following string:

std::string str = "Hello, World!";
int pos = str.find("World");
// Output: pos = 7 (position where "World" starts)
str.erase(5, 2);
// Output: "HelloWorld!"
str.clear();
// Output: "" (empty string)
bool isEmpty = str.empty();
// Returns true if str has no characters
challenge icon

Challenge

Easy

Create a function named stringSearchOperations that takes a string as input and performs the following operations using string functions:

  • Finds and prints the position of the first space character in the string.
  • Erases 4 characters from position 5.
  • Checks if the string contains the word "You" and prints "Found" or "Not Found".
  • Clears the string and checks if it's empty.
  • Prints the results after each operation.

Use the following format:

Space Found At: [Position of space]
After Erase: [String after erasing]
Contains You: [Found/Not Found]
Is Empty: [true/false]

Cheat sheet

Useful string functions in C++:

  • erase(pos, len): Removes len characters starting at position pos
  • find(str): Returns the position of the first occurrence of str (returns -1 if not found)
  • clear(): Removes all characters from the string
  • empty(): Returns true if the string is empty, false otherwise
std::string str = "Hello, World!";

int pos = str.find("World");
// pos = 7 (position where "World" starts)

str.erase(5, 2);
// Result: "HelloWorld!"

str.clear();
// Result: "" (empty string)

bool isEmpty = str.empty();
// Returns true if str has no characters

Try it yourself

#include <iostream>
#include <string>

void stringSearchOperations(std::string str) {
    // Find first space

    // Erase 4 characters from position 5

    // Check if contains "You"

    // Clear string and check if empty
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    stringSearchOperations(str);
    return 0;
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals