C++ Strings
In C++, a string is an object that represents a sequence of characters. Strings can be manipulated using a variety of built-in functions and operators.
Syntax
#include <string>
std::string my_string = "Hello, world!";
Example
#include <iostream>
#include <string>
int main() {
std::string my_string = "Hello, world!";
std::cout << my_string << std::endl;
my_string += " Welcome to C++ strings.";
std::cout << my_string << std::endl;
return 0;
}
Output
Hello, world!
Hello, world! Welcome to C++ strings.
Explanation
In the above example, we have defined a string variable called "my_string" and initialized it with the value "Hello, world!". We then use the +=
operator to concatenate another string onto "my_string" and print the result to the console.
Use
Strings have a wide range of uses in C++, such as:
- Storing and manipulating text data
- Parsing data from files or network streams
- Generating formatted output
#include <iostream>
#include <string>
int main() {
std::string name, address, email;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Enter your address: ";
std::getline(std::cin, address);
std::cout << "Enter your email: ";
std::getline(std::cin, email);
std::cout << "\n\n";
std::cout << "Name: " << name << std::endl;
std::cout << "Address: " << address << std::endl;
std::cout << "Email: " << email << std::endl;
return 0;
}
In this example, we use the std::getline
function to read input from the user and store it into three different string variables. We then print out the values of these variables.
Important Points
- Strings are objects and can be manipulated using a variety of built-in functions and operators.
- String literals are enclosed in double quotes (
"
). - Strings in C++ are null-terminated.
- C++ provides the
std::string
class for working with strings. - The
std::getline
function can be used to read input from the user.
Summary
In summary, strings in C++ are a powerful tool for working with text data. They can be initialized with literals, concatenated with other strings, and manipulated using a wide range of built-in functions and operators. The std::string
class provides a convenient and efficient way to work with strings in C++.