How to initialize a string in C++
What is a string in C++?
The sole purpose of C++ strings is to show a sequence of characters as an object. The characters are kept in the string class as a series of bytes. The <string.h> header file describes a string. Additionally, the character array is only a collection of characters that can be ended by the character NULL. Furthermore, we can add that a stream defines objects that stand in for a stream of text. While the character array's size must be allocated statically, it cannot be allocated at runtime if extra memory is needed.
Initialization of string in C++
A string can be created in C++ with just a few lines of syntax. The string keyword in C++ creates a string. However, we must include the common string class in our program before utilizing this keyword.
Syntax:
string String_Name = "Write the string here";
In addition to the above-mentioned approach, numerous other ways to construct C++ strings exist.
Different ways of Initializing string in C++
Here are the different ways of defining the string in C++, they are as follows:
1. Basic Initialization
string message = "Hello, Friends!";
This initializes a message string with "Hello, Friends!".
2. Using a Constructor
string name("Doremon");
Here, the name represents the variable of value “Doremon”; for defining this string, we used the string keyword.
3. Empty string
string emptyString;
This initializes an empty string called emptyString with no text.
4. Combining String
string firstPart = "Hello, ";
string secondPart = "Friends! ";
string combined = firstPart + secondPart;
You can initialize and combine strings by using the + operator. Here, combined will have the value "Hello, Friends! ".
5. User input
std::string username;
std::cout << "Enter your name: ";
std::cin >> username;
This initializes a username string and allows the user to input their name, which is stored in the string.
6. Character Array
char name_Array[] = "Shinchan";
In this case, you can initialize a string from a character array, name_Array, which contains "Shinchan".
7. Appending to a string
string sentence = "Johny! Johny! Yes, papa";
sentence += " Eating sugar? No papa ";
Here, you start with a string sentence and then append the second part to it using +=. The final value of the sentence will be the complete sentence.
These examples show a variety of string operations in C++, from basic initialization to user input and text manipulation.
String Initializing using Two Methods
There are two types of string representation that C++ offers. They are:
• Character string in C style
• String class types
Character string in C style
A string in the C computer language is an array of characters that concludes with the null or terminate character (\0). The termination is crucial since it informs the compiler of the string's conclusion. Similarly, C++ supports strings in the C-Style. The C-style strings can be created the same way an integer array is created. The syntax is as follows:
Syntax:
char String_Array[5] = {'A', 'r', 'm', 'y', '\0'};
The array's length is one more than the string's since we must include a null character. The string mentioned above can also be defined in the following way:
char String_Array[] = "Army";
Due to adding a null character by C++ at the end of each string, the array String_Array can still hold 5 characters. Using the sizeof() function to determine the array's size will also yield 5.
Example 1:
#include <iostream>
int main() {
const char greeting[] = "Hello, C-Style String!";
std::cout << greeting << std::endl;
return 0;
}
Explanation:
- In this illustration, the string "Hello, C-Style String!" starts a C-style character array called greeting.
- The const keyword ensures that the string is correctly updated.
- The result of the C-style string is "Hello, C-Style String!" after we use std::cout to print its contents.
Output:
![How to initialize a string in C++](https://static.tutorialandexample.com/cpp/how-to-initialize-a-string-in-cpp1.png)
Example 2:
#include <iostream>
#include <cstring>
int main() {
// Initialize a C-style string (character array)
const char cStyleString[] = "C-Style String";
// Print the C-style string
std::cout << "C-Style String: " << cStyleString << std::endl;
return 0;
}
Explanation:
- In this example, we use a character array to initialize the C-style cStyleString. The character array has the string literal "C-Style String" set to it.
- To use C string methods like strlen or strcpy, the cstring header must be included.
- The const keyword ensures that the string is correctly updated.
Output:
![How to initialize a string in C++](https://static.tutorialandexample.com/cpp/how-to-initialize-a-string-in-cpp2.png)
String class types in C++
The C++ library provides a string class type with extensive functionality. It supports all operations.
Example 1:
#include <iostream>
#include <string>
int main() {
std::string greeting = "Hello, std::string!";
std::cout << greeting << std::endl;
return 0;
}
Explanation:
- In this example, we declare a greeting std::string variable and set its initial value to "Hello, std::string!"
- For the std::string class to be used, we must include the string> header.
- Directly allocated to the greeting variable is the string literal "Hello, std::string!"
- The output of "Hello, std::string!" is produced when we use std::cout to print the contents of the std::string.
Output:
![How to initialize a string in C++](https://static.tutorialandexample.com/cpp/how-to-initialize-a-string-in-cpp3.png)
Example 2:
#include <iostream>
#include <string>
int main() {
// Initialize an std::string
std::string cppStyleString = "Hey People";
// Print the std::string
std::cout << " Hey People " << cppStyleString << std::endl;
return 0;
}
Explanation:
- In this example, the std::string class from the C++ Standard Library is used to initialize a std::string called cppStyleString.
- The std::string variable receives a direct assignment of the string value "Hey People".
- Std::string objects, which differ from C-style strings in that they are more flexible and automatically manage memory, are safer and simpler to work with in C++.
Output:
![How to initialize a string in C++](https://static.tutorialandexample.com/cpp/how-to-initialize-a-string-in-cpp4.png)