
Strings are fundamental data types in C++ that represent sequences of characters. They are widely used for handling text data, and C++ provides a rich set of...
Strings are fundamental data types in C++ that represent sequences of characters. They are widely used for handling text data, and C++ provides a rich set of operations to manipulate strings efficiently.
In C++, strings can be represented in two main ways:
C-style Strings: These are arrays of characters terminated by a null character ('\0').
char str[] = "Hello, World!";
C++ Standard Library Strings: The std::string class, part of the C++ Standard Library, provides a more flexible and easier-to-use string representation.
#include <string>
std::string str = "Hello, World!";
C-style Strings:
char str1[] = "Hello";
char str2[6];
strcpy(str2, str1); // Copying str1 to str2
C++ Strings:
#include <string>
std::string str1 = "Hello";
std::string str2 = str1; // Copy assignment
C-style Strings:
char str1[20] = "Hello, ";
char str2[] = "World!";
strcat(str1, str2); // str1 now contains "Hello, World!"
C++ Strings:
std::string str1 = "Hello, ";
std::string str2 = "World!";
std::string result = str1 + str2; // Concatenation
C-style Strings:
int length = strlen(str1); // Returns the length of str1
C++ Strings:
std::string str = "Hello, World!";
size_t length = str.length(); // Returns the length of str
C-style Strings:
char firstChar = str1[0]; // Access first character
C++ Strings:
char firstChar = str[0]; // Access first character
char anotherChar = str.at(1); // Access second character with bounds checking
C++ Strings:
std::string str = "Hello, World!";
std::string sub = str.substr(7, 5); // Extracts "World"
C++ Strings:
size_t position = str.find("World"); // Returns the starting index of "World"
if (position != std::string::npos) {
// Found
}
C-style Strings:
if (strcmp(str1, str2) == 0) {
// Strings are equal
}
C++ Strings:
if (str1 == str2) {
// Strings are equal
}
C++ Strings:
std::string str = "Hello, World!";
str.replace(7, 5, "C++"); // Replaces "World" with "C++"
C++ Strings:
for (char c : str) {
std::cout << c; // Iterate over each character
}
You can use standard input and output streams to work with strings.
Input:
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input); // Read entire line including spaces
Output:
std::cout << "You entered: " << input << std::endl;
Strings in C++ are powerful and flexible tools for handling text data. The std::string class provides a variety of operations for manipulation, including concatenation, searching, and modification. Understanding how to use strings and their associated operations is essential for effective programming in C++. Whether using C-style strings or the more convenient std::string, mastering these operations will enhance your ability to handle textual data in your applications.
Open this section to view and download past papers
Click on Show Past Papers to load available exam papers.