Character String in C++
A character string in C++ is a sequence of characters enclosed in double quotes ("). It is represented by the std::string class in C++. Here's an example:
Code:
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, world!";
std::cout << message << std::endl;
return 0;
}
In the above code, we declare a variable message of type std::string and initialize it with the character string "Hello, world!". We then use the std::cout object to output the contents of message to the console.
C++ also allows you to manipulate character strings using various member functions and operators provided by the std::string class. For example, you can concatenate two strings using the + operator, compare strings using comparison operators like == or <, and access individual characters within a string using the indexing operator [].
Functions of String in C++
Here are the various functions on string in C++:
- String Input:
The method to input the string from the user through the keyboard is known as string input
Code:
#include <iostream>
#include <string>
int main() {
std::string name;
std::cout << "Enter your name: ";
std::getline(std::cin, name);
std::cout << "Hello, " << name << "!" << std::endl;
return 0;
}
In this code, we use the std::getline() function to read a line of input from the user and store it in the name variable. Then we output a greeting message with the entered name.
- String Length:
The length( ) is a function which is used to find the total number of characters present in the given input string
Code:
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, world!";
std::cout << "Length of the string: " << message.length() << std::endl;
return 0;
}
Here, we use the length() member function of the std::string class to determine the length of the string and output it
- String Concatenation:
The method of adding two strings together using the ‘+’ symbol is known as the string concatenation method.
Code:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = " world!";
std::string result = str1 + str2;
std::cout << "Concatenated string: " << result << std::endl;
return 0;
}
In this example, we concatenate two strings str1 and str2 using the + operator and store the result in the result string. The concatenated string is then printed to the console.
- Substring Extraction:
Here, we use the substr() member function to extract a substring from the message string. The first argument specifies the starting position, and the second argument specifies the length of the substring. In this case, we extract the substring "world" starting from index 7.
Code:
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, world!";
std::string substring = message.substr(7, 5);
std::cout << "Substring: " << substring << std::endl;
return 0;
}
- String Comparison:
In this code, we compare two strings str1 and str2 using the == operator. If the strings are equal, we output a message indicating that. Otherwise, we output a different message.
Code:
#include <iostream>
#include <string>
int main() {
std::string str1 = "apple";
std::string str2 = "banana";
if (str1 == str2) {
std::cout << "The strings are equal." << std::endl;
} else {
std::cout << "The strings are not equal." << std::endl;
}
return 0;
}
- String Searching:
Here, we use the find() member function of the std::string class to search for a particular word (fox) within a sentence. If the word is found, we output a message indicating that. Otherwise, we output a different message.
Code:
#include <iostream>
#include <string>
int main() {
std::string sentence = "The quick brown fox jumps over the lazy dog.";
std::string word = "fox";
if (sentence.find(word) != std::string::npos) {
std::cout << "The word '" << word << "' was found in the sentence." << std::endl;
} else {
std::cout << "The word '" << word << "' was not found in the sentence." << std::endl;
}
return 0;
}
- String Conversion:
In this example, we use the std::to_string() function to convert an integer (number) into a string. The resulting string is then printed to the console.
Code:
#include <iostream>
#include <string>
int main() {
int number = 42;
std::string str = std::to_string(number);
std::cout << "The converted string is: " << str << std::endl;
return 0;
}
- String Modification:
Here, we modify a character in the message string by accessing it using the indexing operator [] and assigning a new character to it. In this case, we change the 'w' at index 7 to 'W'
Code:
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, world!";
message[7] = 'W';
std::cout << "Modified string: " << message << std::endl;
return 0;
}
- String Splitting:
In this example, we use an std::istringstream to split a sentence into individual words. The iss object is created with the sentence, and then we use a while loop and the >> operator to extract words from the iss object and store them in a vector. Finally, we print each word from the vector.
Code:
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main() {
std::string sentence = "The quick brown fox";
std::istringstream iss(sentence);
std::vector<std::string> words;
std::string word;
while (iss >> word) {
words.push_back(word);
}
// Printing the split words
for (const auto& w : words) {
std::cout << "Word: " << w << std::endl;
}
return 0;
}
- String Conversion (String to Double):
In this example, we use the std::stod() function to convert a string (numberStr) into a double. The resulting double value is then printed to the console.
Code:
#include <iostream>
#include <string>
int main() {
std::string numberStr = "3.14159";
double number = std::stod(numberStr);
std::cout << "The converted double is: " << number << std::endl;
return 0;
}
- String Replacement:
Here, we use the find() function to search for a specific substring (search) within a string (message). If the substring is found, we use the replace() function to replace it with another string (replacement). The original string and the replaced string are then printed to the console.
Code:
#include <iostream>
#include <string>
int main() {
std::string message = "Hello, world!";
std::string replaced = message;
std::string search = "world";
std::string replacement = "everyone";
size_t pos = replaced.find(search);
if (pos != std::string::npos) {
replaced.replace(pos, search.length(), replacement);
}
std::cout << "Original string: " << message << std::endl;
std::cout << "Replaced string: " << replaced << std::endl;
return 0;
}
- String Padding:
In this example, we pad a string (text) with a specific character (paddingChar) to achieve a desired total width (totalWidth). If the length of the string is less than the total width, we append the required number of padding characters to the string. The resulting padded string is then printed to the console.
Code:
#include <iostream>
#include <string>
int main() {
std::string text = "Hello";
int totalWidth = 10;
char paddingChar = '*';
std::string paddedText = text;
if (paddedText.length() < totalWidth) {
paddedText += std::string(totalWidth - paddedText.length(), paddingChar);
}
std::cout << "Padded string: " << paddedText << std::endl;
return 0;
}
- String to Uppercase:
In this example, we use the std::transform() function from the <algorithm> library to convert a string (text) to uppercase. The ::toupper function is used as the transformation function. The resulting uppercase string is then printed to the console.
Code:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text = "Hello, world!";
std::transform(text.begin(), text.end(), text.begin(), ::toupper);
std::cout << "Uppercase string: " << text << std::endl;
return 0;
}
- String to Lowercase:
In this example, we use the std::transform() function to convert a string (text) to lowercase. The ::tolower function is used as the transformation function. The resulting lowercase string is then printed to the console
Code:
#include <iostream>
#include <string>
#include <algorithm>
int main() {
std::string text = "Hello, world!";
std::transform(text.begin(), text.end(), text.begin(), ::tolower);
std::cout << "Lowercase string: " << text << std::endl;
return 0;
}
- String Repeated Concatenation:
Here, we concatenate a string (word) multiple times based on a given number of repetitions (repetitions). We use a for loop to repeatedly append the string to a new string (repeatedString). The resulting repeated string is then printed to the console.
Code:
#include <iostream>
#include <string>
int main() {
std::string word = "Hello";
int repetitions = 3;
std::string repeatedString;
for (int i = 0; i < repetitions; ++i) {
repeatedString += word;
}
std::cout << "Repeated string: " << repeatedString << std::endl;
return 0;
}
- String Trimming:
In this example, we define a custom function trim() that trims whitespace from the beginning and end of a string. The std::isspace() function is used to check for whitespace characters. The resulting trimmed string is then printed to the console.
Code:
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
// Trim whitespace from the beginning and end of a string
std::string trim(const std::string& str) {
std::string trimmed = str;
trimmed.erase(trimmed.begin(), std::find_if(trimmed.begin(), trimmed.end(), [](int ch) {
return !std::isspace(ch);
}));
trimmed.erase(std::find_if(trimmed.rbegin(), trimmed.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), trimmed.end());
return trimmed;
}
int main() {
std::string text = " Hello, world! ";
std::string trimmedText = trim(text);
std::cout << "Trimmed string: " << trimmedText << std::endl;
return 0;
}
- String Reversal (Without Using Library Functions):
In this example, we define a custom function reverseString() that reverses a string by iterating over its characters from the end and appending them to a new string (reversedStr). The resulting reversed string is then printed to the console.
Code:
#include <iostream>
#include <string>
std::string reverseString(const std::string& str) {
std::string reversedStr;
for (int i = str.length() - 1; i >= 0; --i) {
reversedStr += str[i];
}
return reversedStr;
}
int main() {
std::string message = "Hello, world!";
std::string reversed = reverseString(message);
std::cout << "Reversed string: " << reversed << std::endl;
return 0;
}
- String Palindrome Check:
Here, we define a custom function isPalindrome() that checks whether a string is a palindrome. The function creates a reversed version of the string using the std::reverse() function and then compares it with the original string. If they are the same, the string is considered a palindrome.
Code:
#include <iostream>
#include <string>
#include <algorithm>
bool isPalindrome(const std::string& str) {
std::string reversed = str;
std::reverse(reversed.begin(), reversed.end());
return str == reversed;
}
int main() {
std::string text = "madam";
bool isPalin = isPalindrome(text);
if (isPalin) {
std::cout << "The string is a palindrome." << std::endl;
}
else {
std::cout << "The string is not a palindrome." << std::endl;
}
return 0;
}
- String Character Count:
In this example, we count the occurrences of each character in a string (sentence) and store the counts in an std::unordered_map. We iterate over each character in the string and use the std::isalpha() function to check if it is an alphabet character before incrementing its count in the map. Finally, we print the character counts to the console.
Code:
#include <iostream>
#include <string>
#include <unordered_map>
int main() {
std::string sentence = "Hello, world!";
std::unordered_map<char, int> charCount;
for (char ch : sentence) {
if (std::isalpha(ch)) {
charCount[ch]++;
}
}
// Printing character counts
for (const auto& entry : charCount) {
std::cout << "Character: " << entry.first << ", Count: " << entry.second << std::endl;
}
return 0;
}
- String Conversion (Number to string):
In this example, we convert an integer (number) to its string representation using an std::ostringstream object. The integer is inserted into the oss stream, and then the str() member function is used to retrieve the resulting string. Finally, the string representation of the number is printed to the console.
Code:
#include <iostream>
#include <string>
#include <sstream>
int main() {
int number = 42;
std::ostringstream oss;
oss << number;
std::string strNumber = oss.str();
std::cout << "String representation of number: " << strNumber << std::endl;
return 0;
}
Conclusion:
In conclusion, character strings in C++ are typically managed using the std::string class from the C++ Standard Library. This class provides a modern and convenient way to work with strings of characters, offering a wide range of operations for manipulation and handling. Here's a summary of key points regarding character strings in C++:
- std::string Class: C++ offers the std::string class, which encapsulates a dynamic array of characters along with various member functions to manipulate them.
- Dynamic Size: Unlike C-style strings, std::string automatically manages memory and adjusts its size as needed, eliminating concerns about buffer overflows and memory management issues.
- Concatenation: Strings can be easily concatenated using the + operator or the += assignment operator.
- Length: The length() or size() member functions provide the length of the string.
Overall, std::string simplifies string manipulation in C++ by providing a high-level interface while taking care of memory management and various low-level details. It's a powerful tool for working with character strings, whether for basic text processing or complex string manipulation tasks.