Strings in C++


The C++ string is an object that represents a sequence of characters, each identified by one index.

Creation:

To create strings in C++, you use double quotes like this:

string greeting = "Hello";

Accessing characters:

To access the characters in a string, you use the [] operator

The following example returns the first character of a string with the index zero:

string str = "Hello";
char ch = str[0];
// ch is "H"

Getting the length:

We can get the length of a string using the size() method.

For example, to access the last character of the string, you use the size() - 1 index:

string str = "Hello";
char ch = str[str.size() - 1]; 
// ch is "o"

Concatenating strings via + operator:

To concatenate two or more strings, you use the + operator:

string name = "John";
string str = "Hello " + name;

cout << str << endl; // prints "Hello John"

If you want to assemble a string piece by piece, you can use the += operator:

string greet = "Welcome";
string name = "John";
greet += " to AlgoCademy, ";
greet += name;

cout << greet << endl; // prints "Welcome to AlgoCademy, John"

String slicing

We often want to get a substring of a string. For this, we use the substr() method.

substr(startIndex, endIndex) returns the substring from startIndex to endIndex:

string str = "JavaScript";
string substr = str.substr(2, 6);

cout << substr << endl; // prints "vaSc"

The startIndex is a zero-based index at which the substr() start extraction.

The endIndex is also zero-based index before which the substr() ends the extraction. The substr will not include the character at the endIndex index.

If you omit the endIndex, the substr() extracts to the end of the string:

string str = "JavaScript";
string substr = str.substr(4);

cout << substr << endl; // prints "Script"

Iterating through the characters:

We can iterate throught the characters of a string using a for loop and the : operator like this:

string myStr = "Andy";
for (char c : myStr) {
    cout << c << endl;
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

We can also iterate throught the elements of a string using indices and a for loop like this:

string myStr = "Andy";
for (int i = 0; i < myStr.size(); i++) {
    cout << myStr[i] << endl;
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

Both ways take O(n) time, where n is the length of the array we iterate on.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


Introduction

Strings are a fundamental part of programming, allowing us to work with text data. In C++, the string class provides a rich set of functions to manipulate strings efficiently. Understanding how to use strings is crucial for tasks such as parsing input, generating output, and handling text data in various applications.

Understanding the Basics

Before diving into advanced string manipulations, it's essential to grasp the basic operations. These include creating strings, accessing individual characters, and determining the length of a string. Let's start with some simple examples:

#include <iostream>
#include <string>

int main() {
    // Creating a string
    std::string greeting = "Hello";
    
    // Accessing characters
    char firstChar = greeting[0]; // 'H'
    char lastChar = greeting[greeting.size() - 1]; // 'o'
    
    // Printing the results
    std::cout << "First character: " << firstChar << std::endl;
    std::cout << "Last character: " << lastChar << std::endl;
    
    return 0;
}

Main Concepts

Now that we understand the basics, let's explore some key concepts and techniques for working with strings in C++:

Concatenation

Concatenation is the process of joining two or more strings together. This can be done using the + operator or the += operator:

#include <iostream>
#include <string>

int main() {
    std::string name = "John";
    std::string greeting = "Hello " + name;
    
    std::cout << greeting << std::endl; // prints "Hello John"
    
    std::string welcome = "Welcome";
    welcome += " to AlgoCademy, ";
    welcome += name;
    
    std::cout << welcome << std::endl; // prints "Welcome to AlgoCademy, John"
    
    return 0;
}

String Slicing

String slicing allows us to extract a substring from a string. This is done using the substr() method:

#include <iostream>
#include <string>

int main() {
    std::string str = "JavaScript";
    std::string substr = str.substr(2, 4);
    
    std::cout << substr << std::endl; // prints "vaSc"
    
    substr = str.substr(4);
    std::cout << substr << std::endl; // prints "Script"
    
    return 0;
}

Iterating Through Characters

We can iterate through the characters of a string using a for loop. There are two common ways to do this:

#include <iostream>
#include <string>

int main() {
    std::string myStr = "Andy";
    
    // Using range-based for loop
    for (char c : myStr) {
        std::cout << c << std::endl;
    }
    
    // Using index-based for loop
    for (int i = 0; i < myStr.size(); i++) {
        std::cout << myStr[i] << std::endl;
    }
    
    return 0;
}

Examples and Use Cases

Let's look at some practical examples and use cases where string manipulation is essential:

Example 1: Reversing a String

Reversing a string is a common task. Here's how you can do it:

#include <iostream>
#include <string>

int main() {
    std::string str = "Hello";
    std::string reversedStr;
    
    for (int i = str.size() - 1; i >= 0; i--) {
        reversedStr += str[i];
    }
    
    std::cout << "Reversed string: " << reversedStr << std::endl;
    
    return 0;
}

Example 2: Checking for Palindrome

A palindrome is a string that reads the same backward as forward. Here's how to check for a palindrome:

#include <iostream>
#include <string>

bool isPalindrome(const std::string& str) {
    int left = 0;
    int right = str.size() - 1;
    
    while (left < right) {
        if (str[left] != str[right]) {
            return false;
        }
        left++;
        right--;
    }
    
    return true;
}

int main() {
    std::string str = "radar";
    
    if (isPalindrome(str)) {
        std::cout << str << " is a palindrome" << std::endl;
    } else {
        std::cout << str << " is not a palindrome" << std::endl;
    }
    
    return 0;
}

Common Pitfalls and Best Practices

When working with strings, it's important to be aware of common pitfalls and follow best practices:

Advanced Techniques

Once you're comfortable with the basics, you can explore advanced string manipulation techniques:

Using std::stringstream

std::stringstream allows for efficient string concatenation and manipulation:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;
    ss << "Hello" << " " << "World";
    
    std::string result = ss.str();
    std::cout << result << std::endl; // prints "Hello World"
    
    return 0;
}

Debugging and Testing

Debugging and testing are crucial for ensuring the correctness of your string manipulations:

Example: Testing a Palindrome Function

#include <iostream>
#include <cassert>
#include <string>

bool isPalindrome(const std::string& str);

void testIsPalindrome() {
    assert(isPalindrome("radar") == true);
    assert(isPalindrome("hello") == false);
    assert(isPalindrome("level") == true);
    assert(isPalindrome("world") == false);
    std::cout << "All test cases passed!" << std::endl;
}

int main() {
    testIsPalindrome();
    return 0;
}

Thinking and Problem-Solving Tips

When solving string-related problems, consider the following tips:

Conclusion

Mastering string manipulation in C++ is essential for handling text data effectively. By understanding the basics, exploring advanced techniques, and following best practices, you can write efficient and maintainable code. Keep practicing and experimenting with different string operations to enhance your skills further.

Additional Resources

For further reading and practice, consider the following resources: