43: ***(Syntax)*** Some useful ---string--- methods
- .length( )
.length( ) function tells you the length of the string.
#include <iostream>using namespace std;int main(){ int charcters; string word;
cout << "Enter a word: "; getline(cin, word);
cout << "There are " << word.length() << " characters in word: " << word;
return 0;}- .empty( )
.empty( ) function is a boolean attribute that is used when you have to check whether the user have given some input or not
#include <iostream>using namespace std;int main(){
string name;
cout << "Enter your name: "; getline(cin, name);
if(name.empty()){ cout << "You didn't write anything \n"; } else cout << "Welcome " << name;
return 0;}In this program, if no input is given by the user, You didn't write anything will be the output. Otherwise, Welcome name will be the output.
- .clear( )
.empty( ) function is a boolean attribute that is used when you have to check whether the user have given some input or not
In this program, if no input is given by the user, You didn't write anything will be the output. Otherwise, Welcome name will be the output.
.clear( ) is used to clear everything from the variable with which it is written.
Now, in this program, when we used .clear( ) function, everything within name string was deleted and the output will be: Your name is: only
- .append( )
.append( ) is used to add some predefined text in the string. To add the text you have to add that text between ( ) of .append( )
For example, You want to add @gmail.com after the name entered by the user:
whatever the name is written by the user, in output, there will be @gmail.com
- .at( )
.at( ) is used to check which character is on the certain position number in a string.
Note. counting starts from 0
- .insert( )
.insert( ) is used to insert a character in a string
To do this in ( ) first write index(serial of character before which you have to insert character. This starts from 0 ie first character is at position 0) then add a comma then add what you want to insert within " "
- .find(' ')
This is used to find first white space in the string.
remember index number starts from 0.
- .erase( )
This is used to remove specific portion of a string.
In ( ) write starting index, then comma, then ending index.
Comments
Post a Comment