C++ Strings:
In C++, a string is a sequence of characters, typically used to store and manipulate text. Unlike C, which uses character arrays to represent strings, C++ provides a built-in string class called std::string
. This class is part of the Standard Template Library (STL) and offers various features for working with strings.
1. String Concatenation:
String concatenation is the process of joining two or more strings to create a new string. In C++, you can use the +
operator to concatenate strings. Here's an example:
In this example, str1 + str2
concatenates the two strings, resulting in "Hello, world!".
2. C++ Numbers and Strings:
You can convert numbers (integers or floating-point values) to strings using the std::to_string
function. This function converts a number to its string representation. Example:
3. C++ String Length:
To find the length (number of characters) of a string, you can use the length()
or size()
member functions of std::string
. Example:
4. C++ Access Strings:
You can access individual characters in a C++ string using array-like indexing. Strings are zero-indexed. Example:
5. C++ Special Characters:
C++ strings can contain special characters like newline (\n
), tab (\t
), and others. These characters are represented as escape sequences within the string. Example:
6. C++ User Input Strings:
To read a string from the user, you can use the std::cin
stream along with the >>
operator. Example:
7. C++ String Namespace:
The C++ Standard Library provides the std
namespace, which contains the string
class and other standard C++ features. You can access the string
class by prefixing it with std::
, as shown in the previous examples.
Remember to include the <string>
and <iostream>
headers to work with C++ strings and perform input/output operations. C++ strings are more convenient and flexible than C-style character arrays for handling text data in your programs.