String Operations in C++
Strings are a special kind of objects in std::string class. It is a collection of characters in a common name.
Features:
- The manipulation is easy. You can access, concatenate strings, extract a substring and compare them quickly.
- It has many built-in functions.
- You can add or remove characters according to the user need. It adopt it effectively.
How to create and manipulate Strings?
First, include header file #include<string>
Next, declare a string as follows..
Syntax:
‘string str;’
Where string is the keyword to represent string.
‘str’ is the variable.
Eg:
‘string a;’
C++ Program to print string:
#include <iostream>
#include <string>
using namespace std;
int main() {
string
a="Welcome to C++";
cout<<a;
return 0;
}
Output:
Welcome to C++
The operations of strings are given below.
- · Accessing of an element.
- · Concatenating strings
- · Length of string
- · Modification of string
- · Substring extraction
- · Searching an element
Accessing of an element:
It accesses
the element in the string.
C++ Program:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str =
"Welcome to the world of C++";
cout<<str<<endl;
cout <<
"First character: " << str[0] << endl;
cout <<
"Sixth character: " << str[6] << endl;
cout <<
"Character at index 10: " << str.at(10) << endl;
}
Output:
Welcome to the world of C++
First character: W
Sixth character: e
Character at index 9: o
Strings in C++
Concatenating strings:
Two
strings are joined together here.
C++ program:
#include <iostream>
#include <string>
using namespace std;
int main() {
string st1 =
"C++";
string st2 =
" Programming";
string cat = st1 +
st2;
cout <<
"Concatenation of two strings are : " << cat << endl;
string res1 = st1;
res1.append(st2);
cout <<
"Concatenation of two strings using append() functions: " <<
res1 << endl;
return 0;
}
Output:
Concatenation of two strings are : C++ Programming
Concatenation of two strings using append() functions: C++
Programming
These are the basic operations of Strings in c++ programming
was explained. Part2 is explained in next post.
Comments
Post a Comment