String is a collection of characters. There are two types of strings commonly used in C++ programming language:
C-strings (C-style Strings)
In C programming, the collection of characters is stored in the form of arrays. This is also supported in C++ programming. Hence it's called C-strings.
C-strings are arrays of type char terminated with null character, that is, \0 (ASCII value of null character is 0).
Strings that are objects of string class (The Standard C++ Library string class)
In C++, you can also create a string object for holding strings.
Unlike using char arrays, string objects has no fixed length, and can be extended as per your requirement.
The C++ string class, std::string, provides a flexible way to handle strings in a more object-oriented manner compared to traditional C-style strings.
String Class in C++
The string class is huge and includes many constructors, member functions, and operators.
Programmers may use the constructors, operators and member functions to achieve the following:
Creating string objects
Reading string objects from keyboard
Displaying string objects to the screen
Finding a substring from a string
Modifying string
Adding objects of string
Comparing strings
Accessing characters of a string
Obtaining the size or length of a string, etc...
Example:
#include <iostream>
#include <string> // Include the string library
using namespace std;
int main() {
// Initialize strings
string str1 = "Hello"; // First string
string str2 = "World"; // Second string
string str3; // Third string for concatenation
// Copy str1 into str3
str3 = str1;
cout << "str3 : " << str3 << endl; // Output: Hello
// Concatenate str1 and str2
str3 = str1 + " " + str2;
cout << "str1 + str2 : " << str3 << endl; // Output: Hello World
// Get the length of str3 after concatenation
int len = str3.size();
cout << "str3.size() : " << len << endl; // Output: 11
return 0;
}
Initialization: The strings str1 and str2 are initialized with the values "Hello" and "World", respectively.
Copying Strings: The value of str1 is copied into str3.
Concatenation: The two strings are concatenated with a space in between, and the result is stored in str3.
Length Calculation: The size() method is used to determine the length of str3, which includes the space between "Hello" and "World".
Dynamic Size: Unlike C-style strings, which require a fixed size, std::string can grow and shrink dynamically.
Member Functions: It includes various member functions such as .size(), .append(), .push_back(), and more for manipulating strings easily.
Operator Overloading: You can use operators like + for concatenation directly with string objects.
The strcmp() function is a standard C library function that compares two C-style strings lexicographically. It returns:
0 if both strings are equal.
A negative value if the first string is less than the second.
A positive value if the first string is greater than the second.
Example:
#include <iostream>
#include <cstring>
int main() {
const char *str1 = "Apple";
const char *str2 = "Orange";
if (strcmp(str1, str2) == 0) {
std::cout << "Both strings are equal." << std::endl;
} else {
std::cout << "The strings are not equal." << std::endl;
}
return 0;
}
The compare() method is a member function of the std::string class that compares two strings. It returns:
0 if both strings are equal.
A negative value if the first string is smaller.
A positive value if the first string is larger.
Example:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "Hello";
int result = str1.compare(str2);
if (result == 0) {
std::cout << "Strings are equal." << std::endl;
} else if (result < 0) {
std::cout << "String 1 is less than String 2." << std::endl;
} else {
std::cout << "String 1 is greater than String 2." << std::endl;
}
return 0;
}
C++ allows direct comparison of std::string objects using relational operators such as ==, !=, <, and >. This method is straightforward and intuitive.
Example:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Banana";
std::string str2 = "Apple";
if (str1 == str2) {
std::cout << "Strings are equal." << std::endl;
} else {
std::cout << "Strings are not equal." << std::endl;
}
return 0;
}
To manipulate strings in C++, including converting to uppercase, lowercase, and reversing them, you can utilize the C++ Standard Library's string class and its functions. Here’s a concise guide on how to achieve these tasks.
C++ provides built-in functions to convert characters to uppercase and lowercase. You can use std::toupper() and std::tolower() from the <cctype> header.
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
for (char &c : str) {
c = toupper(c); // Convert each character to uppercase
}
cout << "Uppercase: " << str << endl;
return 0;
}
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
for (char &c : str) {
c = tolower(c); // Convert each character to lowercase
}
cout << "Lowercase: " << str << endl;
return 0;
}
To reverse a string in C++, you can use the std::reverse() function from the <algorithm> header, or you can implement your own method.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
reverse(str.begin(), str.end()); // Reverse the string using STL function
cout << "Reversed: " << str << endl;
return 0;
}
#include <iostream>
#include <string>
using namespace std;
int main() {
string str;
cout << "Enter a string: ";
getline(cin, str);
// Manual reversal using two-pointer technique
int left = 0, right = str.length() - 1;
while (left < right) {
swap(str[left], str[right]); // Swap characters
left++;
right--;
}
cout << "Reversed: " << str << endl;
return 0;
}
Escape sequences
Escape sequences are used in the programming languages C and C++, and their design was copied in many other languages such as Java, PHP, C#, etc.
An escape sequence is a sequence of characters that does not represent itself when used inside a character or string literal, but is translated into another character or a sequence of characters that may be difficult or impossible to represent directly.
In C++, all escape sequences consist of two or more characters, the first of which is the backslash, \ (called the "Escape character"); the remaining characters determine the interpretation of the escape sequence.
length() / size(): Returns the number of characters in the string.
std::string str = "Hello";
std::cout << str.length(); // Outputs: 5
at(index): Returns the character at the specified index with bounds checking.
operator[]: Returns the character at the specified index without bounds checking.
char ch = str.at(1); // ch = 'e'
char ch2 = str[1]; // ch2 = 'e'
append(str): Appends str to the end of the current string.
insert(index, str): Inserts str at the specified index.
replace(start, length, str): Replaces part of the string starting at start with str. Also length specifies how much of the other part of the string should be erased. If the length is zero, it will rather append the word to the section of the string.
erase(start, length): Removes characters from the string starting at start.
str.append(" World"); // "Hello World"
str.insert(5, ","); // "Hello, World"
str.replace(7, 5, "Universe"); // "Hello, Universe"
str.erase(5, 1); // "Hello Universe"
find(substring): Returns the index of the first occurrence of substring, or std::string::npos if not found.
rfind(substring): Returns the index of the last occurrence of substring.
size_t pos = str.find("Universe"); // pos = 6
substr(start, length): Returns a substring starting from start with a specified length.
std::string sub = str.substr(7, 8); // "Universe"
c_str(): Returns a C-style string (null-terminated).
to_string(value): Converts numeric values to a string.
const char* cstr = str.c_str();
std::string numStr = std::to_string(42); // "42"
compare(str): Compares two strings lexicographically.
Operators (==, !=, <, >, etc.): Allow for direct comparison between strings.
if (str.compare("Hello") == 0) {
std::cout << "Strings are equal.";
}
empty(): Checks if the string is empty.
clear(): Clears the contents of the string.
resize(new_size): Changes the size of the string to new_size.
capacity(): Returns the size of storage space currently allocated for the string.