Lesson 41 of 60 – String Functions in C++
68%

String Functions in C++

C++ provides several useful functions and methods for working with strings. These functions can be used to find the length of a string, search for text, extract parts of a string, insert or remove text, compare strings, and perform other common string operations.

Note: Most string operations in this lesson use std::string. Include the <string> header before using it.

1. What are String Functions?

String functions are functions and methods used to perform operations on text stored in a std::string.

For example:

std::string name = "Rahul";

std::cout << name.length();

The length() function returns the number of characters in the string.

2. Include the String Header

To use std::string, include the string header.

#include <iostream>
#include <string>

You can then create and manipulate string objects.

3. length() Function

The length() function returns the number of characters in a string.

std::string text = "Hello";

std::cout << text.length();

Output:

5

4. size() Function

The size() function also returns the number of characters in a std::string.

std::string text = "Computer";

std::cout << text.size();

Output:

8

For std::string, size() and length() return the same count.

5. empty() Function

The empty() function checks whether a string contains no characters.

std::string name;

if (name.empty()) {

    std::cout << "String is empty";
}

It returns true if the string is empty.

6. clear() Function

The clear() function removes all characters from a string.

std::string message = "Hello World";

message.clear();

std::cout << message;

After calling clear(), the string becomes empty.

7. at() Function

The at() function accesses a character at a specified position.

std::string word = "Hello";

std::cout << word.at(1);

Output:

e

Indexes start from 0.

8. Accessing Characters with []

Characters can also be accessed using the square bracket operator.

std::string word = "Hello";

std::cout << word[0];

Output:

H

Both at() and [] can access characters, but they differ in their handling of an out-of-range index.

9. find() Function

The find() function searches for a character or substring.

std::string text = "Hello World";

std::size_t position = text.find("World");

if (position != std::string::npos) {

    std::cout << "Found";
}

If the text is not found, find() returns std::string::npos.

10. find() with a Character

std::string word = "Computer";

std::size_t position = word.find('p');

std::cout << position;

The function returns the index of the first matching character.

For "Computer", the character p is found at index 3.

11. find() with a Starting Position

You can specify where the search should start.

std::string text = "apple apple";

std::size_t position =
    text.find("apple", 1);

std::cout << position;

The search starts from index 1, so the second occurrence can be found.

12. rfind() Function

The rfind() function searches for the last occurrence of a character or substring.

std::string text = "apple apple";

std::size_t position =
    text.rfind("apple");

std::cout << position;

It searches from the end of the string toward the beginning.

13. substr() Function

The substr() function extracts part of a string.

std::string text = "Programming";

std::string part =
    text.substr(0, 7);

std::cout << part;

Output:

Program

The first argument is the starting position and the second is the number of characters.

14. substr() Without Length

If the second argument is omitted, substr() returns the characters from the starting position to the end.

std::string text = "Hello World";

std::string part =
    text.substr(6);

std::cout << part;

Output:

World

15. append() Function

The append() function adds text to the end of a string.

std::string text = "Hello";

text.append(" World");

std::cout << text;

Output:

Hello World

16. insert() Function

The insert() function adds text at a specified position.

std::string text = "Hello World";

text.insert(6, "C++ ");

std::cout << text;

Output:

Hello C++ World

17. erase() Function

The erase() function removes characters from a string.

std::string text = "Hello World";

text.erase(5, 6);

std::cout << text;

Output:

Hello

The first argument is the starting position and the second is the number of characters to remove.

18. replace() Function

The replace() function replaces part of a string with another string.

std::string text = "I like Java";

text.replace(7, 4, "C++");

std::cout << text;

Output:

I like C++

19. compare() Function

The compare() function compares two strings.

std::string first = "Apple";
std::string second = "Apple";

if (first.compare(second) == 0) {

    std::cout << "Strings are equal";
}

A result of 0 means the strings are equal.

20. String Comparison Operators

Strings can also be compared using operators such as ==, !=, <, and >.

std::string a = "Apple";
std::string b = "Banana";

if (a < b) {

    std::cout << "Apple comes before Banana";
}

String comparisons are based on the ordering of their character values.

21. swap() Function

The swap() function exchanges the contents of two strings.

std::string first = "Hello";
std::string second = "World";

first.swap(second);

std::cout << first << std::endl;
std::cout << second;

Output:

World
Hello

22. push_back() Function

The push_back() function adds one character to the end of a string.

std::string text = "Hell";

text.push_back('o');

std::cout << text;

Output:

Hello

23. pop_back() Function

The pop_back() function removes the last character from a non-empty string.

std::string text = "Hello";

text.pop_back();

std::cout << text;

Output:

Hell

24. c_str() Function

The c_str() function provides access to a null-terminated character sequence representing the string.

std::string text = "Hello";

const char* value = text.c_str();

std::cout << value;

It is useful when interacting with APIs that require a C-style string.

25. Counting a Character

A loop and at() or indexing can be used to count how many times a character appears.

std::string text = "banana";

int count = 0;

for (int i = 0; i < text.length(); i++) {

    if (text[i] == 'a') {
        count++;
    }
}

std::cout << "Count = "
          << count;

Output:

Count = 3

26. Common String Function Mistakes

  • Forgetting to include <string>.
  • Using an invalid string index.
  • Confusing the string length with the last index.
  • Forgetting that find() returns std::string::npos when the item is not found.
  • Calling pop_back() on an empty string.
  • Using std::cin >> when a complete line with spaces is required.
  • Using incorrect positions with erase(), insert(), or replace().

27. Practical Search Program

#include <iostream>
#include <string>

int main() {

    std::string sentence;

    std::cout << "Enter a sentence: ";

    std::getline(std::cin, sentence);

    std::string searchText;

    std::cout << "Enter text to search: ";

    std::getline(std::cin, searchText);

    std::size_t position =
        sentence.find(searchText);

    if (position != std::string::npos) {

        std::cout << "Text found at index "
                  << position;
    }
    else {

        std::cout << "Text not found";
    }

    return 0;
}

28. Practical String Modification Program

#include <iostream>
#include <string>

int main() {

    std::string text = "Hello World";

    text.replace(6, 5, "C++");

    std::cout << text << std::endl;

    text.append(" Programming");

    std::cout << text;

    return 0;
}

Output:

Hello C++
Hello C++ Programming

29. Best Practices for String Functions

  • Use std::string for normal string processing.
  • Use length() or size() when you need the string length.
  • Check the result of find() against std::string::npos.
  • Use substr() to extract portions of text.
  • Use append() or += to add text.
  • Use erase() and replace() carefully with correct positions.
  • Use empty() before operations that require a non-empty string when appropriate.
  • Use std::getline() when input can contain spaces.

30. String Functions – Final Summary

Function Purpose
length() Returns the number of characters.
size() Returns the number of characters.
empty() Checks whether the string is empty.
clear() Removes all characters.
at() Accesses a character at a position.
find() Searches for a character or substring.
rfind() Searches for the last occurrence.
substr() Extracts part of a string.
append() Adds text to the end.
insert() Inserts text at a position.
erase() Removes characters.
replace() Replaces part of a string.
compare() Compares two strings.
swap() Exchanges two strings.
push_back() Adds one character at the end.
pop_back() Removes the last character.
c_str() Provides a C-style character sequence.

📌 Key Points

  • C++ provides many useful functions for working with strings.
  • length() and size() return the number of characters.
  • empty() checks whether a string has no characters.
  • clear() removes all characters from a string.
  • find() searches for text and returns its position when found.
  • substr() extracts a portion of a string.
  • append() and insert() add text.
  • erase() removes characters and replace() replaces text.
  • compare() can be used to compare strings.
  • push_back() and pop_back() work with the final character.

🧠 Quick Quiz

Question: Which function is used to search for a character or substring inside a C++ string?