Strings
C++ String Operations
Declaration and Initialization:
#include <iostream>
#include <string>
int main() {
// Declaration and initialization of a string
std::string greeting = "Hello, World!";
// Displaying the string
std::cout << greeting << std::endl;
return 0;
}
In C++, strings are sequences of characters represented by the std::string
class. Strings are more flexible than character arrays and provide several built-in functions for string manipulation.
String Input/Output:
#include <iostream>
#include <string>
int main() {
std::string name;
// Input
std::cout << "Enter your name: ";
std::cin >> name;
// Output
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
You can use the standard input/output operations with strings.
Concatenation:
#include <iostream>
#include <string>
int main() {
std::string first = "Hello";
std::string second = "World";
// Concatenation using the + operator
std::string result = first + ", " + second + "!";
// Displaying the result
std::cout << result << std::endl;
return 0;
}
Strings can be concatenated using the +
operator or the append
function.
String Length:
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, World!";
// Using length() function
std::cout << "Length of the string: " << message.length() << std::endl;
return 0;
}
The length()
function or size()
function can be used to get the length of a string.
String Access:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, World!";
// Accessing characters using []
std::cout << "First character: " << greeting[0] << std::endl;
std::cout << "Third character: " << greeting[2] << std::endl;
return 0;
}
Individual characters in a string can be accessed using the []
operator.
String Comparison:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
// Comparing strings
if (str1 == str2) {
std::cout << "Strings are equal." << std::endl;
} else {
std::cout << "Strings are not equal." << std::endl;
}
return 0;
}
Strings can be compared using relational operators (==
, !=
, <
, >
, <=
, >=
).
String Manipulation:
#include <iostream>
#include <string>
int main() {
std::string sentence = "The quick brown fox jumps over the lazy dog";
// Extracting a substring
std::string word = sentence.substr(10, 5); // Extract "brown"
// Finding the position of a substring
size_t position = sentence.find("fox"); // Find the position of "fox"
// Replacing a substring
sentence.replace(position, 3, "cat"); // Replace "fox" with "cat"
// Displaying the modified string
std::cout << sentence << std::endl;
return 0;
}
C++ provides a rich set of string manipulation functions through the std::string
class. Familiarizing yourself with these functions allows you to work effectively with strings in C++ programs.