CPlusPlus / Strings

CPlusPlus / Strings#

  1. What is string concatenation? How do you perform string concatenation in C++?

    String concatenation is the operation of combining two or more strings to create a single, longer string. In C++, there are several ways to perform string concatenation:

    1. With the + operator: This is the most straightforward method for std::string objects.

    std::string str1 = "Hello";
    std::string str2 = "World";
    std::string result = str1 + " " + str2;  // result is "Hello World"
    
    1. Using the append() method:

    std::string str1 = "Hello";
    str1.append(" World");  // str1 is now "Hello World"
    
    1. Using the += operator:

    std::string str1 = "Hello";
    str1 += " World";  // str1 is now "Hello World"
    
  2. How do you find a substring within a string?

    Using the find() method. Example: str.find(“substring”)

  3. What’s the purpose of the capacity() method?

    It returns the number of characters that the string can hold without requiring reallocation.

  4. How do you convert a string to an integer?

    Using the std::stoi() function. Example: int num = std::stoi(str)

  5. What’s the difference between push_back() and append() for std::string?

    push_back() adds a single character, while append() can add multiple characters or another string.

  6. What’s the difference between erase() and clear() for std::string?

    erase() can remove a portion of the string, while clear() removes all characters.