Strings in C++ Programming
What is a String in C++ ?
A string in C++ is an array of characters terminated by a null character ('\0'
). Strings are used to store text, and they are a fundamental data type in C++ programming. Strings in C++ are represented using the char
data type.
- String Declaration: Strings are declared using an array of
char
elements. For example:char str[20];
- String Initialization: You can initialize a string by directly assigning it with a string literal:
char str[] = "Hello";
Algorithm :-
str
with "Hello".("%s", str)
.Example 1: Declaring and Initializing a String
Definition: In this example, we declare a string and initialize it with a string literal.
This example demonstrates how to declare a string and assign a value to it.
Expected Behavior: The program stores the string "Hello" in the array str
.
#include <iostream> int main() { char str[] = "Hello"; std::cout << str; // Print the string return 0; }
Algorithm :-
str1
with "Hello, ". str2
with "World!".str1 += str2
to concatenate str2
to str1
.std::cout << str1
.Example 2: Manipulating Strings in C++
Definition: Strings in C++ can be manipulated using the standard string class, which provides built-in operations for string manipulation.
This example demonstrates string concatenation using the C++ string class.
Expected Behavior: The program will concatenate two strings and print the resulting string.
#include <iostream> #include <string> int main() { std::string str1 = "Hello, "; std::string str2 = "World!"; str1 += str2; // Concatenate str2 to str1 std::cout << str1; // Print the concatenated string return 0; }
Algorithm :-
str
with "Hello".str.length()
and store it.cout << "Length of string: " << str.length()
.Example 3: Finding the Length of a String
Definition: The length()
member function is used to determine the length of a string in C++.
This example demonstrates how to use length()
to find the length of a string.
Expected Behavior: The program will print the length of the string "Hello".
#include <iostream> #include <string> int main() { std::string str = "Hello"; std::cout << "Length of string: " << str.length(); // Print the length of the string return 0; }
Algorithm :-
str1
with "Hello" and str2
with "World".str1
and str2
using compare()
.Example 4: Comparing Strings
Definition: The compare()
member function is used to compare two strings lexicographically in C++. It returns 0 if the strings are equal, a positive value if the first string is greater, and a negative value if the second string is greater.
This example demonstrates how to compare two strings using compare()
.
Expected Behavior: The program will compare two strings and print whether they are equal or which one is lexicographically greater.
#include <iostream> #include <string> int main() { std::string str1 = "Hello"; std::string str2 = "World"; if (str1.compare(str2) == 0) { std::cout << "Strings are equal"; } else { std::cout << "Strings are not equal"; } return 0; }