Menu
Coddy logo textTech

String Functions Part 1

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

Here are some useful functions in strings:

  • insert(pos, str): Inserts the string str at position pos in the current string.
  • replace(pos, len, str): Replaces len characters starting at position pos with the string str.
  • substr(pos, len): Returns a substring of the current string, starting at position pos and having length len.
  • append(str): Adds the string str to the end of the current string.

For example using the following string:

std::string str = "Hello, World!";
str.insert(5, " C++");
// Output: "Hello C++, World!"
str.replace(7, 5, "Universe");
// Output: "Hello, Universe!"
str.substr(0, 5);
// Output: "Hello"
str.substr(7, 5);
// Output: "World"
str.substr(7);
// Output: "World!"
str.append(" This is universe");
// Output: "Hello, World! This is universe"
challenge icon

Challenge

Easy

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

  1. Prints the length of the string.
  2. Appends the string " - Modified" to the original string.
  3. Inserts the string "C++ " at the beginning of the string.
  4. Extracts a substring of length 5 starting at position 5.
  5. Replaces the occurrence of the substring of length 5 start at position 5 with the string "Awesome".
  6. Prints the modified string after each operation.

Use the following format:

Length: [Length of string]
Append: [After Appending]
Insert: [After Insert]
Extract: [The extracted string]
Replace: [After replacing]

Cheat sheet

Useful C++ string functions:

  • insert(pos, str): Inserts string str at position pos
  • replace(pos, len, str): Replaces len characters starting at position pos with string str
  • substr(pos, len): Returns substring starting at position pos with length len
  • append(str): Adds string str to the end
std::string str = "Hello, World!";

str.insert(5, " C++");
// "Hello C++, World!"

str.replace(7, 5, "Universe");
// "Hello, Universe!"

str.substr(0, 5);
// "Hello"

str.append(" This is universe");
// "Hello, World! This is universe"

Try it yourself

#include <iostream>
#include <string>

void stringOperations(std::string str) {
    // 1. Print length of the string

    // 2. Append " - Modified" to the string

    // 3. Insert "C++ " at the beginning

    // 4. Extract substring of length 5 starting at position 5

    // 5. Replace substring at position 5 with "Awesome"
    
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    stringOperations(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