Home C++ C++ strings tutorial with code examples

C++ strings tutorial with code examples

In C++, strings are used to handle sequences of characters.

C++ provides two main ways to work with strings: C-style strings (character arrays) and C++ string objects (from the std::string class in the Standard Template Library).

C++ strings offer a wide range of functionality and are generally preferred over C-style strings for their ease of use and flexibility.

1. C-style Strings (Character Arrays)

C-style strings are character arrays ending with a null character (‘\0’).

#include <iostream>
using namespace std;

int main() {
    // Initialize C-style string
    char greeting[] = "Hello, World!";
    
    // Display the string
    cout << greeting << endl;

    return 0;
}

Explanation:

  • greeting is a character array initialized with “Hello, World!”.
  • C-style strings must end with a null character (‘\0’) to indicate the end of the string.

Output:

Hello, World!

2. C++ Strings (std::string)

The std::string class from the <string> library provides a more versatile way to work with strings.

#include <iostream>
#include <string>
using namespace std;

int main() {
    // Initialize C++ string
    string greeting = "Hello, World!";
    
    // Display the string
    cout << greeting << endl;

    return 0;
}

Explanation:

  • std::string is part of the C++ Standard Library, making string manipulation easier and safer than using character arrays.

Output:

Hello, World!

3. Getting the Length of a String

The length() and size() functions return the number of characters in a std::string.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello, C++!";

    cout << "Length of the string: " << text.length() << endl;

    return 0;
}

Explanation:

  • text.length() returns the number of characters in the string.

Output:

Length of the string: 10

4. Accessing Characters in a String

You can access characters in a std::string using the [] operator or the at() method.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello, C++!";
    
    // Accessing characters using []
    cout << "First character: " << text[0] << endl;

    // Accessing characters using at()
    cout << "Fourth character: " << text.at(3) << endl;

    return 0;
}

Explanation:

  • text[0] accesses the first character, and text.at(3) accesses the fourth character.

Output:

First character: H
Fourth character: l

5. Concatenating Strings

The + operator or the append() method can be used to concatenate strings.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string firstName = "John";
    string lastName = "Doe";

    // Using + operator
    string fullName = firstName + " " + lastName;
    cout << "Full Name: " << fullName << endl;

    // Using append()
    fullName = firstName.append(" ").append(lastName);
    cout << "Full Name (using append): " << fullName << endl;

    return 0;
}

Explanation:

  • + concatenates two strings.
  • append() also concatenates strings and allows chaining multiple strings together.

Output:

Full Name: John Doe
Full Name (using append): John Doe

6. Comparing Strings

You can compare strings using ==, !=, or the compare() method.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string str1 = "apple";
    string str2 = "orange";

    // Using == operator
    if (str1 == str2) {
        cout << "The strings are equal." << endl;
    } else {
        cout << "The strings are not equal." << endl;
    }

    // Using compare() method
    int result = str1.compare(str2);
    if (result == 0) {
        cout << "The strings are equal." << endl;
    } else if (result < 0) {
        cout << "str1 is less than str2." << endl;
    } else {
        cout << "str1 is greater than str2." << endl;
    }

    return 0;
}

Explanation:

  • == checks if two strings are equal.
  • compare() returns 0 if strings are equal, a negative value if str1 is less than str2, and a positive value if str1 is greater.

Output:

The strings are not equal.
str1 is less than str2.

7. Finding a Substring

The find() method searches for a substring within a string and returns the starting index of the first match.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello, C++ World!";
    
    size_t found = text.find("C++");
    if (found != string::npos) {
        cout << "'C++' found at position: " << found << endl;
    } else {
        cout << "'C++' not found." << endl;
    }

    return 0;
}

Explanation:

  • text.find(“C++”) searches for “C++” and returns the starting index if found. If not found, it returns string::npos.

Output:

'C++' found at position: 7

8. Extracting a Substring

The substr() method extracts a substring from a string, given a starting index and optional length.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello, C++ World!";
    
    string sub = text.substr(7, 3); // Start at index 7, length 3
    cout << "Substring: " << sub << endl;

    return 0;
}

Explanation:

  • text.substr(7, 3) extracts a substring starting at index 7 with a length of 3 characters.

Output:

Substring: C++

9. Replacing Part of a String

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

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "I love Java!";
    
    // Replace "Java" with "C++"
    text.replace(7, 4, "C++");
    cout << text << endl;

    return 0;
}

Explanation:

  • text.replace(7, 4, “C++”) replaces 4 characters starting at index 7 with “C++”.

Output:

I love C++!

10. Inserting into a String

The insert() method inserts a string at a specified position.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "I love programming!";
    
    // Insert "C++ " at index 7
    text.insert(7, "C++ ");
    cout << text << endl;

    return 0;
}

Explanation:

  • text.insert(7, “C++ “) inserts “C++ ” at index 7 in the string.

Output:

I love C++ programming!

11. Removing Characters from a String

The erase() method removes a portion of a string, given a starting index and optional length.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "I love C++ programming!";
    
    // Remove "C++ "
    text.erase(7, 4);
    cout << text << endl;

    return 0;
}

Explanation:

  • text.erase(7, 4) removes 4 characters starting at index 7.

Output:

I love programming!

12. Converting Between Strings and Numbers

You can convert between strings and numbers using to_string() and stoi() functions.

#include <iostream>
#include <string>
using namespace std;

int main() {
    int number = 42;
    string text = to_string(number); // Convert int to string
    cout << "String: " << text << endl;

    string strNum = "123";
    int num = stoi(strNum); // Convert string to int
    cout << "Integer: " << num << endl;

    return 0;
}

Explanation:

  • to_string() converts a number to a string.
  • stoi() converts a string to an integer.

Output:

String: 42
Integer: 123

13. Iterating Over a String

You can use a loop to iterate through each character in a string.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "Hello, C++!";
    


    for (char c : text) {
        cout << c << " ";
    }
    cout << endl;

    return 0;
}

Explanation:

  • A range-based for loop iterates through each character in text.

Output:

H e l l o ,   C + + !

14. Checking if a String is Empty

The empty() method checks if a string is empty.

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text = "";

    if (text.empty()) {
        cout << "The string is empty." << endl;
    } else {
        cout << "The string is not empty." << endl;
    }

    return 0;
}

Explanation:

  • text.empty() returns true if text is empty, otherwise false.

Output:

The string is empty.

Summary Table of Common String Operations

Operation Example Code Description
Initialize String string text = “Hello”; Creates a new string
Get Length text.length() Returns number of characters
Access Character text[0] or text.at(0) Access a character by index
Concatenate text + ” World” or text.append() Combine strings
Compare Strings text1 == text2 or text1.compare() Compare two strings
Find Substring text.find(“C++”) Locate a substring
Extract Substring text.substr(7, 3) Extract part of a string
Replace Substring text.replace(7, 3, “Python”) Replace part of a string
Insert Substring text.insert(7, “C++ “) Insert substring at a position
Remove Substring text.erase(7, 4) Remove part of a string
Convert to String to_string(123) Convert number to string
Convert to Number stoi(“123”) Convert string to integer
Check if Empty text.empty() Check if string is empty
Iterate Over String for (char c : text) { … } Loop through each character in string

Key Takeaways

  • C++ strings (std::string) offer more functionality and flexibility compared to C-style strings.
  • Common operations like concatenation, finding substrings, replacing, and inserting are easy to perform with std::string.
  • Conversion functions like to_string() and stoi() are useful for working with strings and numbers interchangeably.
  • The <string> library provides powerful functions to manipulate strings for a variety of applications.

 

You may also like