String Manipulation
String manipulation refers to the various operations that can be performed on strings to modify them. In C++, there are several ways to manipulate strings.
Length of a String
The length of a string can be obtained using the length()
function. It returns the number of characters in the string.
Here's an example:
1std::string str = "Hello, World!";
2int length = str.length();
Accessing Characters
Individual characters in a string can be accessed using their index. The index starts at 0 for the first character and goes up to length() - 1
for the last character.
Here's an example:
1std::string str = "Hello, World!";
2char firstChar = str[0]; // Accessing the first character
3char lastChar = str[str.length() - 1]; // Accessing the last character
Substring
A substring is a portion of a larger string. The substr()
function can be used to extract a substring from a string. It takes two parameters: the starting index and the length of the substring.
Here's an example:
1std::string str = "Hello, World!";
2std::string substring = str.substr(7, 5); // Extracting the substring starting from index 7 with length 5
Concatenation
Concatenation is the process of combining two or more strings into a single string. In C++, you can concatenate strings using the +
operator.
Here's an example:
1std::string str1 = "Hello, ";
2std::string str2 = "World!";
3std::string concat = str1 + str2; // Concatenating str1 and str2
xxxxxxxxxx
int main() {
std::string str = "Hello, World!";
// Length of the string
int length = str.length();
std::cout << "Length: " << length << std::endl;
// Accessing characters
char firstChar = str[0];
char lastChar = str[str.length() - 1];
std::cout << "First character: " << firstChar << std::endl;
std::cout << "Last character: " << lastChar << std::endl;
// Substring
std::string substring = str.substr(7, 5);
std::cout << "Substring: " << substring << std::endl;
// Concatenation
std::string concat = str + " Welcome to C++!";
std::cout << "Concatenated string: " << concat << std::endl;
return 0;
}