-
-
Notifications
You must be signed in to change notification settings - Fork 1
Strings
String is a data type used to represent a sequence of characters. It is an important part of the C++ language and is used to store, manipulate and process textual data. Strings are immutable objects, which means that once created, they cannot be changed.
The basic syntax of a string in C++ is as follows:
string str = "string content";
This declares a string object named str
and assigns it the value of string content
.
C++ strings have a number of useful methods that can be used to manipulate strings.
The length()
method can be used to retrieve the length of a string. This method returns an integer value representing the number of characters in the string.
string str = "string content";
int len = str.length();
The above code assigns the value 12
to the variable len
.
The +
operator can be used to concatenate two strings. This creates a new string that is the combination of the two strings.
string str1 = "Hello";
string str2 = "World";
string str3 = str1 + " " + str2;
The above code assigns the value Hello World
to the variable str3
.
The substr()
method can be used to extract a substring from a string. This method takes two parameters: an integer representing the starting position of the substring and an integer representing the length of the substring.
string str = "string content";
string sub = str.substr(0, 6);
The above code assigns the value string
to the variable sub
.
Strings are an important part of the C++ language and offer a number of useful methods for manipulating and processing textual data.