Lesson 40 of 60 – Strings in C++
67%

Strings in C++

A string is a sequence of characters used to store text such as names, addresses, messages, sentences, and other textual information. In modern C++, the std::string class is commonly used for working with strings.

Note: To use std::string, include the <string> header file.

1. What is a String?

A string is a sequence of characters. For example:

"Hello"
"Rahul"
"Welcome to C++"

Strings are used whenever a program needs to work with text.

2. Including the String Header

The std::string class is provided by the <string> header.

#include <iostream>
#include <string>

After including the header, we can create string variables.

3. Declaring a String

std::string name;

Here, name is a string variable that can store text.

Example:

std::string city = "Aurangabad";

4. Initializing a String

A string can be initialized when it is declared.

std::string name = "Amit";

The string "Amit" is stored in the variable name.

5. Printing a String

#include <iostream>
#include <string>

int main() {

    std::string name = "Rahul";

    std::cout << name;

    return 0;
}

Output:

Rahul

6. Taking a Single Word as Input

The >> operator can be used to read a string from the user. It reads input up to whitespace.

std::string name;

std::cout << "Enter your name: ";
std::cin >> name;

std::cout << "Hello "
          << name;

If the user enters Rahul, the program stores that word in the string.

7. Reading a Full Line

Use std::getline() when you want to read a complete line, including spaces.

std::string fullName;

std::cout << "Enter your full name: ";

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

std::cout << fullName;

For example, Rahul Kumar can be read as one complete string.

8. String with Spaces

std::string message =
    "Welcome to C++ Programming";

std::cout << message;

A std::string can contain spaces and multiple words.

9. Finding String Length

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

std::string name = "Rahul";

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

Output:

5

10. Using size() with Strings

The size() function can also be used to get the number of characters in a string.

std::string word = "Computer";

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

Output:

8

For a std::string, size() and length() provide the same count of characters.

11. Accessing String Characters

Individual characters can be accessed using an index.

std::string word = "Hello";

std::cout << word[0];

Output:

H

Like arrays, string indexes start from 0.

12. Accessing the Last Character

std::string word = "Hello";

std::cout << word[word.length() - 1];

Output:

o

The last character is located at index length() - 1.

13. Changing a Character

Characters in a non-const std::string can be changed using an index.

std::string word = "Hello";

word[0] = 'Y';

std::cout << word;

Output:

Yello

14. Looping Through a String

A for loop can be used to process each character.

std::string word = "Hello";

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

    std::cout << word[i] << std::endl;
}

Output:

H
e
l
l
o

15. Joining Two Strings

The + operator can be used to concatenate strings.

std::string firstName = "Rahul";
std::string lastName = "Kumar";

std::string fullName =
    firstName + " " + lastName;

std::cout << fullName;

Output:

Rahul Kumar

16. Appending Text with +=

The += operator can add text to the end of a string.

std::string message = "Hello";

message += " World";

std::cout << message;

Output:

Hello World

17. Comparing Strings

Strings can be compared using operators such as == and !=.

std::string password = "admin";

if (password == "admin") {

    std::cout << "Correct password";

}

The == operator checks whether two strings have the same content.

18. Checking if Two Strings Are Different

std::string city1 = "Patna";
std::string city2 = "Delhi";

if (city1 != city2) {

    std::cout << "Cities are different";
}

The != operator checks whether the strings are different.

19. Finding a Character with find()

The find() function can be used to search for a character or substring.

std::string word = "Computer";

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

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

    std::cout << "Character found";
}

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

20. Finding a Word in a String

std::string sentence =
    "I am learning C++";

std::size_t position =
    sentence.find("C++");

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

    std::cout << "C++ found";
}

The find() function can search for a sequence of characters inside a string.

21. Substring with substr()

The substr() function extracts part of a string.

std::string word = "Programming";

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

std::cout << part;

Output:

Program

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

22. Removing Text with erase()

The erase() function can remove characters from a string.

std::string word = "Hello World";

word.erase(5, 6);

std::cout << word;

Output:

Hello

The first argument specifies the starting position and the second specifies how many characters to remove.

23. Inserting Text with insert()

The insert() function inserts characters into a string.

std::string word = "Hello World";

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

std::cout << word;

Output:

Hello C++ World

24. Replacing Text with replace()

The replace() function can replace part of a string.

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

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

std::cout << text;

Output:

I like C++

25. Clearing a String

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

std::string message = "Hello World";

message.clear();

std::cout << message;

After clear(), the string is empty.

26. Checking Whether a String Is Empty

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

std::string name;

if (name.empty()) {

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

It returns true when the string has no characters.

27. Practical Full Name Program

#include <iostream>
#include <string>

int main() {

    std::string firstName;
    std::string lastName;

    std::cout << "Enter first name: ";
    std::cin >> firstName;

    std::cout << "Enter last name: ";
    std::cin >> lastName;

    std::string fullName =
        firstName + " " + lastName;

    std::cout << "Full Name: "
              << fullName;

    return 0;
}

28. Practical Sentence Input Program

#include <iostream>
#include <string>

int main() {

    std::string sentence;

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

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

    std::cout << "You entered: "
              << sentence << std::endl;

    std::cout << "Length: "
              << sentence.length();

    return 0;
}

std::getline() is useful when the input may contain spaces.

29. Best Practices for Strings

  • Use std::string for normal text processing.
  • Include the <string> header when using std::string.
  • Use std::getline() when spaces need to be included in input.
  • Remember that string indexes start at 0.
  • Check a string's length before accessing an index when necessary.
  • Use find() for searching text.
  • Use empty() to check whether a string has no characters.
  • Use meaningful names for string variables.

30. Strings – Final Summary

Concept Meaning
std::string Common C++ type for storing text.
length() Returns the number of characters in a string.
size() Also returns the number of characters in a string.
getline() Reads a complete line, including spaces.
find() Searches for a character or substring.
substr() Extracts part of a string.
erase() Removes characters from a string.
insert() Inserts text into a string.
replace() Replaces part of a string.
clear() Removes all characters from a string.
#include <iostream>
#include <string>

int main() {

    std::string message =
        "Hello C++";

    std::cout << message;

    return 0;
}

📌 Key Points

  • A string stores a sequence of characters.
  • std::string is commonly used for text in modern C++.
  • The <string> header is used with std::string.
  • String indexes start from 0.
  • length() and size() return the number of characters.
  • std::getline() can read a complete line containing spaces.
  • The + operator can concatenate strings.
  • find() searches for characters or substrings.
  • substr(), erase(), insert(), and replace() can modify or extract string content.
  • clear() removes all characters from a string.

🧠 Quick Quiz

Question: Which function is commonly used to read a complete line of text, including spaces?