C++-style Strings

‮ptth‬s://www.theitroad.com

In C++, the string class is a powerful and convenient way to work with strings. Here's an example of creating a string:

#include <string>

std::string myString = "Hello, world!";

In this example, we're creating a string object called myString and initializing it with the string "Hello, world!".

You can access individual characters in a string using the same array notation as C-style strings:

#include <string>

std::string myString = "Hello, world!";

char firstCharacter = myString[0]; // firstCharacter is 'H'

In this example, we're accessing the first character of the string ('H') using array notation.

You can also modify individual characters in a string using array notation:

#include <string>

std::string myString = "Hello, world!";

myString[0] = 'J'; // the first character of the string is now 'J'

In this example, we're modifying the first character of the string, changing it from 'H' to 'J'.

string objects provide a number of useful methods for working with strings. For example, you can concatenate two string objects using the + operator:

#include <string>

std::string firstName = "John";
std::string lastName = "Doe";

std::string fullName = firstName + " " + lastName; // fullName is "John Doe"

In this example, we're creating two string objects, firstName and lastName, and concatenating them with a space to create a full name.

string objects also provide methods for finding substrings, converting between uppercase and lowercase, and many other operations. It's generally recommended to use string instead of C-style strings when working with strings in C++.