What Is String?
A string is a data type used in programming such as int, float, char, but it is used to represent text rather than numbers.
How to initialize string?
Program:
string str = "bybeastcoder";
cout << str;
Output:
bybeastcoder
Program:
string str;
cout << "Enter any string: ";
cin >> str;
cout << "Entered String is: " << str;
Output:
Enter any String: Work Hard
Entered String is: Work
In above program we entered "Work Hard" but it printed just "Work". So to get more than one word or to get a sentence we will use a predefined function "getline();"
Program:
string str;
cout << "Enter any String: ";
getline (cin,str);
cout << "Entered String is: "<< str;
Output:
Enter any String: Work Hard
Entered String is: Work Hard
How to add two strings?
There are two ways to add strings 1) using ' append() ' function and 2) using ' + ' operator.
Program:
string s1 = "progr"; string s2 = "amming"; s1.append (s2); //append function used to add two strings cout << "Sum of s1 and s2 is: " << s1;
string s1 = "progr"; string s2 = "amming"; cout << s1 + s2;
Output:
Sum of s1 and s2 is: programming
programming
New Function is empty() & clear() :-
To check whether the string is empty or not we use a predefined function called ' empty() '. Here we will use one more function to clear the string called ' clear() '. So let's see how to implement it.
#include <iostream>
using namespace std;
int main ()
{
string s = "C++ Programs";
cout << s << endl;
//if s.empty() gives '0' it means string is not empty
//and if s.empty() gives '1' it means string is empty
cout << s.empty () << endl;
s.clear ();
cout << s.empty () << endl;
return 0;
}
C++ Programs
0
1
New Function is erase() and find() :-
What erase() and find() function do? It erases n characters present in any string from the given index. And find() function finds the input characters and outputs starting index.(remember that indexing starts from zero)
string s = "fashion"; cout &tl;< s.find ("io") << endl; s.erase (2, 3);
//1st argument is index and 2nd is number of chars to be deleted
cout << s;
4
faon
C++ Program To Implement String I
Reviewed by Beast Coder
on
March 11, 2021
Rating:
No comments: