Strings
Strings
string s1;
s1=“high school”;
string s2= “high school”;
string s3(“high school”);
In c++ there is new class called string. Its an
improvement on C-strings. It removes some of
the limitations of C-Strings.
• There is no need to create the array of the
right size to hold string variables.
Contd…….
• The String class assumes all the responsibility
for memory management.
• It allows the use of overloaded operators,so
we can concatinate string objects with +
operator.
Eg:- s3=s1+s2
• It is more efficient and easy to use than C-
strings.
#include<iostream>
#include<string>
using namespace std;
main()
{
string s1("man");
string s2=“hi";
string s3;
s3=s1;
cout<<"s3="<<s3<<endl;
s1.insert(4, s2);
s1.append(s2); cout<<s1<<endl;
cout<<s1<<endl;
s1.erase(4, 5);
s1.append(s2,1,2); cout<<s1<<endl;
cout<<s1;
s2.replace(1, 3, s1);
cout<<s2<<endl;
return 0; return 0;
String Characteristics
Function Task
size() Number of elements currently stored
length() Number of elements currently stored
#include<string>
using namespace std;
int main()
{
string str=“This is a c++ programming";
cout<< "bytes = " <<sizeof(str)<<endl;
#include<string>
using namespace std;
int main()
{ string str1="welcome";
string str2="welldone";
int x=str1.compare(str2);
if(x==0)
cout<<“Strings are same";
else
if (str1.compare(str2) != 0)
cout << str1 << " is not " << str2 << '\n';
if (str1.compare(6,5,"apple") == 0)
if (str1.compare(6,5,str2,4,5) == 0)
return 0;
}
Accessing Characters in Strings
Function Task
at() For accessing individual characters
substr() For retrieving a substring
find() For finding a specific substring
rfind() For finding a specific substring from right
find_first_of() For finding the location of first occurrence of the specific
character(s)
find_last_of() For finding the location of last occurrence of the specific
character(s)
getline() For taking the string object value from user standred io function
find() and substr()
#include<iostream> #include<iostream>
#include<string> #include<string>
using namespace std;
using namespace std;
cout<< str1.find("ve")<<endl;
cout<< str1.rfind("ve")<<endl<<endl;
cout<<str1.find_first_of('l')<<endl;
cout<<str1.find_last_of('l')<<endl<<endl;
}
find() and substr()
int main () {
int x =str1.find(str2);
cout<<x<<endl;
int y= temp.find(str2);
cout<<y; // or cout<<y + x + str2.size();
}
getline
• string s;
• cout<<“Enter string”;
• getline(cin,s);
What is the difference between unsigned int length() and
unsigned int size()?
a) 20
b) 23
c) 25
d) 21
• Choose the correct answer:
1. char str1[] = {‘H’, ’e’, ’l’, ’l’, ’o’, ’\0’};
2. char str2[]=“Hello”;
3. string str3(“hello”);