CPP

Strings in C++ - Basic String Operations


Strings are used to work with text data in C++. C++ provides a powerful standard library for handling strings, including various operations for creating, manipulating, and displaying text. In this guide, we'll explore the basics of strings in C++.

String Declaration and Initialization

You can declare and initialize strings in C++ using the std::string class. Here's how to create and initialize strings:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string greeting = `Hello, world!`;
    string name(`Alice`);
    cout << greeting << endl;
    cout << `My name is ` << name << endl;
    return 0;
}
    

In this example, we create and initialize two strings, greeting and name.

String Concatenation

You can concatenate strings using the + operator or the append() method:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string firstName = `John`;
    string lastName = `Doe`;
    string fullName = firstName + ` ` + lastName;
    fullName.append(` Jr.`);
    cout << fullName << endl;
    return 0;
}
    

In this example, we concatenate the first name, last name, and a suffix to create the full name.

String Length

You can find the length of a string using the length() method or the size() method:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string text = `This is a sample text.`;
    int length = text.length();
    int size = text.size();
    cout << `Length: ` << length << endl;
    cout << `Size: ` << size << endl;
    return 0;
}
    

Both length() and size() return the number of characters in the string.

String Substring

You can extract a substring from a string using the substr() method:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string sentence = `C++ programming is fun!`;
    string substring = sentence.substr(4, 11);
    cout << `Original: ` << sentence << endl;
    cout << `Substring: ` << substring << endl;
    return 0;
}
    

In this example, we extract a substring starting at index 4 and with a length of 11 characters.

String Find

You can search for a substring within a string using the find() method:

#include <iostream>
#include <string>
using namespace std;
int main() {
    string text = `The quick brown fox jumps over the lazy dog.`;
    size_t found = text.find(`fox`);
    if (found != string::npos) {
        cout << `Substring found at position ` << found << endl;
    } else {
        cout << `Substring not found.` << endl;
    }
    return 0;
}
    

The find() method returns the position of the first occurrence of the substring, or string::npos if not found.

Conclusion

Working with strings is a fundamental aspect of C++ programming. As you continue your C++ journey, you'll explore more advanced string operations and learn to handle text data effectively.

Written by Surfside Media

Senior Full Stack Developer specializing in Web Technologies.