Class String and StringStream Processing in C++

The C++ template class basic_string provides a typical string that provides typical string-manipulation operations such as copying, searching, etc. The template definition and all support facilities are defined in namespace std; these include the typedef statement

typedef basic_string<char> string;

that creates the alias type string for basic_string<char>. A typedef also is provided for the wchar_t type. Type wchar_t stores characters(e.g. two-byte characters four-byte characters, etc.) for supporting other character sets. To use strings, include header file <string>

A string object can be initialized with a constructor argument such as

             string text("Hello");    // creates string from const char

This creates a string containing the characters in “Hello” except, the terminating ‘\0’, or with two constructor arguments as in

string name(8,'x');   //string of 8 'x' characters

which creates a string containing eight ‘x‘ characters. The class string also provides a default constructor and copy constructor

A string also can be initialized by the alternate construction syntax in the definition of a string as in

string month="March";   //same as:string month("March")

Attempting to convert an int or char to a string by an assignment in a declaration or by a constructor argument is a syntax error.

So let us see the different type of String Class Program Such as:

1.Program of string Assignment and Concatenation
2.Program of Comparing strings in C++
3.Program of Substrings
4.Program of Swapping strings
5.Program of string Characteristics
6.Program for Finding Strings and characters in a string
7.Program of Replacing Characters in a string
8.Program of Inserting Characters into a string
9.Program of Conversion to C-style char *Strings
10.Iterators
11.String Stream Processing

1.Program of string Assignment and Concatenation in C++

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
int main()
{
string string1("cat");
string string2;
string string3;

string2=string1;
string3.assign(string1);
cout<<"string1:"<<string1<<"\nstring2:"<<string2
    <<"\nstring3:"<<string3<<"\n\n";

string2[0]=string3[2]='r';
cout<<"After modification of string2 and string3:\n"
    <<"string1:"<<string1<<"\nstring2:"<<string2
    <<"\nstring3:";
//demonstrating member function at
for(int  i=0;i<string3.length();i++)
  cout<<string3.at(i);
//declare string4 and string5
string string4(string1+"apult");
string string5;
//overloaded +=
string3 +="pet";  //create "carpet"
string1.append("acomb");  //create "catacomb"
string5.append(string1,4,string1.length());
cout<<"\n\nAfter concatenation:\nstring1:"<<string1
    <<"\nstring2:"<<string2<<"\nstring3:"
    <<string3<<"\nstring4:"<<string4
    <<"\nstring5:"<<string5<<endl;
return 0;
}

OUTPUT:

string1:cat
string2:cat
string3:cat

After modification of string2 and string3:
string1: cat
string2: rat
string3: car

After concatenation:
string1:catacomb
string2:rat
string3:carpet
string4:catapult
string5:comb

Accessing a string subscript outside the bounds of the string using the function at throws an out_of_range exception.

Accessing an element beyond the size of the string using the subscript operator is a logic error

2.Program of Comparing strings in C++

#include <iostream>
using std::cout;
using std::endl;
#include<string>

using std::string;
int main()
{
string string1("Testing the comparision function.");
string string2("Hello");
string string3("stinger");
string string4(string2);
cout<<"string1:"<<string1<<"\nstring2:"<<string2
    <<"\nstring3:"<<string3<<"\nstring4:"<<string4
    <<"\n\n";
if(string1==string4)
cout<<"string1 is equal string4";
else
{
if(string1>string4)
cout<<"string1 is greater than string4\n";
else
cout<<"string1 is less than string4\n";
}
int result=string1.compare(string2);
if(result==0)
cout<<"string1.compare(string2) is equal to 0\n";
else
if(result>0)
cout<<"string1.compare(string2) is greater than 0\n";
else
cout<<"string1.compare(string2) is less than 0\n";
result=string1.compare(2,5,string3,0,5);
if(result==0)
cout<<"string1.compare(2,5,string3,0,5)==0\n";
else
if(result>0)
cout<<"string1compare(2,5,string3,0,5)>0\n";
else
cout<<"string1.compare(2,5,string3,0,5)<0\n";

//comparing string2 and string4
result=string4.compare(0,string2.length(),string2);
if(result==0)
cout<<"string4.compare(0,string2.length())";
    <<"(string2)==0"<<endl;
else
if(result>0)
cout<<"string4.compare(0,string2.length())";
    <<"(string2)>0"<<endl;
else
cout<<"string4.compare(0,string2.length())";
    <<"(string2)<0"<<endl;
result=string2.compare(0,3,string4);
if(result==0)
cout<<"string2.compare(0,3,string4)==0"<<endl;
else
if(result>0)
cout<<"string2.compare(0,3,string4)>0"<<endl;
else
cout<<"string2.compare(0,3,string4)<0"<<endl;
return 0;
}

OUTPUT:

string1:Testing the comparison functions.
string2:Hello
string3:stinger
string4:Hello
string1>string4
string1.compare(string2)>0
string1.compare(2,5,string3,0,5)==0
string4.compare(0,string2.length(),string2)==0
string2.compare(0,3,string4)<0

3.Program of Substrings in C++

Class string provides member function substr for retrieving a substring from a string

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
int main()
{
string string1("The airplane landed on the time");
//begins at subscript 7 and consists of 5 elements
cout<<string1.substr(7,5)<<endl;
return 0;
}

OUTPUT:

plane

4.Program of Swapping strings in C++

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;

int main()
{
string first("one");
string second("two");
cout<<"Before swap:\nfirst:"<<first
    <<"\nsecond:"<<second;
first.swap(second);
cout<<"\n\nAfter swap:\nfirst:"<<first
    <<"\nsecond:"<<second<<endl;
return 0;
}

OUTPUT:

Before swap:
 first:one
second:two

After swap:
 first:two
second:one

5.Program of string Characteristics in C++

Class string provides member functions for gathering information about a string’s size, length, capacity, maximum length, and another characteristic. A string’s size or length is the number of characters currently stored in the string. A string’s capacity is the total number of characters that can be stored in the string without the string requiring additional memory. The maximum size is the largest possible size a string can have. If this value is exceeded, a length_error exception is thrown.

#include<iostream>
using std::cout;
using std::endl;
using std::cin;
using std::boolalpha;
#include<string>
using std::string;
void printStatistics(const string &);
int main()
{
string string1;
cout<<"Statistics before input:\n"<<boolalpha;
printStatistics(string1);
cout<<"\n\nEnter a string:";
cin>>string1;
cout<<"The string entered was:"<<string1;
cout<<"\nStatistics after input:\n";
printStatistics(string1);
cin>>string1;
cout<<"\n\nThe remaining string is:"<<string1<<endl;
printStatistics(string1);
string1 +="123456";
cout<<"\n\nstring1 is now:"<<string1<<endl;
printStatistics(string1);
string1.resize(string1.length()+10);
cout<<"\n\nStats after resizing by (length+10):\n";
printStatistics(string1);
cout<<endl;
return 0;
}
void printStatistics(const string &stringRef)
{
cout<<"capacity:"<<stringRef.capacity()
    <<"\nmax size:"<<stringRef.max_size()
    <<"\nsize:"<<stringRef.size()
    <<"\nlength:"<<stringRef.length()
    <<"\nempty:"<<stringRef.empty();
}

OUTPUT:

Statistics before input:                                                                                                        
 capacity:0                                                                                                                      
 max size:4611686018427387897                                                                                                    
 size:0                                                                                                                          
 length:0                                                                                                                        
 empty:true                                                                                                                      
 Enter a string:Learn Programming                                                                                                
 The string entered was:Learn                                                                                                    
 Statistics after input:                                                                                                         
 capacity:8                                                                                                                      
 max size:4611686018427387897                                                                                                    
 size:5                                                                                                                          
 length:5                                                                                                                        
 empty:false                                                                                                                     
 The remaining string is:Programming                                                                                             
 capacity:16                                                                                                                     
 max size:4611686018427387897                                                                                                    
 size:11                                                                                                                         
 length:11                                                                                                                       
 empty:false                                                                                                                     
 string1 is now:Programming123456                                                                                                
 capacity:32                                                                                                                     
 max size:4611686018427387897                                                                                                    
 size:17                  
 length:17                                                                                                                       
 empty:false                                                                                                                     
 Stats after resizing by (length+10):                                                                                            
 capacity:32                                                                                                                     
 max size:4611686018427387897                                                                                                    
 size:27                                                                                                                         
 length:27                                                                                                                       
 empty:false                                                                                                                     

To minimize the number of times the memory is allocated and deallocated, some string class implementations provide a default capacity above and beyond the length of the string

6.Program for Finding Strings and characters in a string in C++

Class string provides const member functions for finding substrings and characters in a string

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
int main()
{
string string1("noon is 12 p.m");
int location;
cout<<"Original string:\n"<<string1
    <<"\n\n(find)\"is\"was found at:"
    <<string1.find("is")
    <<"\n(rfind)\"is\"was found at:"
    <<string1.rfind("is");

location=string1.find_first_of("misop");
cout<<"\n\n(find_first_of)found"<<string1[location]
    <<"from the group\"misop\"at:"
    <<location;
 
location=string1.find_last_of("misop");
cout<<"\n\n(find_last_of)found"<<string1[location]
    <<"from the group\"misop\"at:"
    <<location;
 
location=string1.find_first_not_of("noi spm");
cout<<"\n\n(find_first_not_of)"<<string1[location]
    <<"is not contained in \noi spm\"and was found at:"
    <<location;

location=string1.find_first_not_of("12noi spm");
cout<<"\n\n(find_first_not_of)"<<string1[location]
    <<"is not contained in \"12noi spm\" and was"
    <<"found at:"<<location<<endl;

location=string1.find_first_not_of("noon is 12 p.m.");
cout<<"\nfind_first_not_of(\"noon is 12 p.m.\")"
    <<"returned:"<<location<<endl;
return 0; 
}

OUTPUT:

Original string:
noon is 12 p.m.
(find) "is" was found at:5
(rfind) "is" was found at:5
(find_first_of) found 'o' from the group "misop" at:1
(find_last_of) found 'm' from the group "misop" at:13
(find_first_not_of) '1' is not contained in "noi spm" and was found
at:8
(find_first_not_of) '.' is not contained in "12noi spm" and was found
at:12
find_first_not_of("noon is 12 p.m.") returned:-1 

7.Program of Replacing Characters in a string in C++

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;

int main()
{
sring string1("The values in any left subtree"
            "\nare less than the value in the"
            "\nparent node and the values in"
            "\nany right subtree are greater"
            "\nthan the value in the parent node");
cout<<"Original string:\n"<<string1<<endl<<endl;
string1.erase(62);
cout<<"Original string after erase:\n"<<string1
    <<"\n\nAfter first replacement:\n";
int position=string1.find(" ");
while(position!=string::npos)
{
string1.replace(position,1,".");
position=string1.find(" ",position+1);
}
cout<<string1<<"\n\nAfter second replacement:\n";
position=string1.find(".");
while(position!=string::npos)
{
string1.replace(position,2,"xxxxx;;yyyyy",5,2);
position=string1.find(".",position+1);
}
cout<<string1<<endl;
return 0;
}

OUTPUT:

Original string:
The values in any left subtree
are less than the value in the
parent node and the values in
any right subtree are greater
than the value in the parent node

Original string after erase:
The values in any left subtree
are less than the value in the

After first replacement:
The.values.in.any.left.subtree
are.less.than.the.value.in.the

After second replacement:
The;;alues;;n;;ny;;eft;;ubtree
are;;ess;;han;;he;;alue;;n;;he  

8.Program of Inserting Characters into a string

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
int main()
{
string string1("beginning end");
string string2("middle");
string string3("12345678");
string string4("xx");
cout<<"Initial strings:\nstring1:"<<string1
    <<"\nstring2:"<<string2<<"\nstring3:"<<string3
    <<"\nstring4:"<<string4<<"\n\n";
string1.insert(10,string2);
string3.insert(3,string4,0,string::npos);
cout<<"Strings after insert:\nstring1:"<<string1
    <<"\nstring2:"<<string2<<"\nstring3:"<<string3
    <<"\nstring4:"<<string4<<endl;
return 0;
}

OUTPUT:

Initial strings:
string1:beginning end
string2:middle
string3:12345678
string4:xx
String after insert:
string1:beginning middle end
string2:middle
string3:123xx45678
string4:xx

9.Program of Conversion to C-style char *Strings in C++

Class string provides member functions for converting strings to C-style strings. As mentioned earlier, unlike C-style strings, they are not necessarily null-terminated. These conversion functions are useful when a given function takes a C-style string as an argument.

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
int main()
{
string sytring1("STRINGS");
const char *ptr1=0;
int length=string1.length();
char *ptr2=new char[length+1];
string1.copy(ptr2,length,0);
ptr2[length]='\0';
cout<<"string s is"<<string1
    <<"\nstring1 converted to a C-Style string is"
    <<string1.c_str()<<"\nptr1 is";
ptr1=string1.data();
for(int i=0;i<length;i++)
cout<<*(ptr1+1);
cout<<"\nptr2 is"<<ptr2<<endl;
delete[] ptr2;
return 0;
}

OUTPUT:

string s is STRINGS
string1 converted to a C-Style string is STRINGS
ptr1 is STRINGS
ptr2 is STRINGS

Not terminating the character array returned by data with a null character can lead to execution-time errors

Whenever possible, use the more robust strings rather than C-style strings

Converting strings that contain one or more null characters to C-style strings can cause logic errors because null characters are interpreted as terminators for C-style strings

10.Iterators in C++

Class string provides iterators for forwarding and backward traversal of strings. Iterators provide access to individual characters with syntax that is similar to pointer operations. Iterators are not range checked.

A Simple Program of Iterator in C++

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
int main()
{
string string1("Testing Iterators");
string::const_iterator iterator1=string1.begin();
cout<<"string1="<<string1
    <<"\n(Using iterator iterator) string1 is:";
while(iterator1!=string1.end())
{
cout<<*iterator1;
++iterator1;
}
cout<<endl;
return 0;
}

OUTPUT:

string1=Testing iterators
(Using iterator1)string1 is:Testing iterators

Use string member function at(rather than iterators) when you want the benefit of range checking

11.String Stream Processing in C++

In, addition to standard stream I/O and file stream I/O, C++ stream I/O includes capabilities for inputting from strings in memory and outputting to strings in memory. These capabilities often are referred to as in-memory I/O or string stream processing.
Input from a string is supported by class istringstream.Output to a string is supported by class ostringstream.The class names istringstream and ostringstream are actually aliases. These names are defined with the typedefs

typedef basic_istringstream<char>istringstream;
typedef basic_ostringstream<char>ostringstream;

Classes basic_istringsstream and basic_ostringstream provide the same functionality as classes istream and ostream plus other member functions specific to in-memory formatting.Programs that use in-memory formatting must include the <sstream> and <iostream> header files.

One application of these techniques is data validation. A program can read an entire line at a time from the input stream into a string. Next, a validation routine can scrutinize the contents of the string and correct(or repair) the data, if necessary. Then the program can proceed to input from the string, knowing that the input data is in the proper format
Outputting to a string is a nice way to take advantage of the power output formatting capabilities of C++ streams. Data can be prepared in a string to mimic the edited screen format. That string could be written to a disk file to preserve the screen image.

Program of StringStream Processing

#include<iostream>
using std::cout;
using std::endl;
#include<string>
using std::string;
#include<sstream>
using std::ostringstream;
int main()
{
ostringstream outputString;
string string1("Output of several data types");
string string2("to an ostringstream object:");
string string3("\n   double");
string string4("\n    int:");
string string5("\naddress of int:");
double double1=123.4567
int integer=22;
outputString<<string1<<string2<<string3<<double1
            <<string4<<integer<<string5<<&integer;
cout<<"outputString contains:"<<outputString.str();
outputString<<"\nmore character added";
         cout<<"\n\nafter additional stream insertion,\n"
             <<"outputString contains:\n"<<outputString.str()
             <<endl;
return 0;
}

OUTPUT:

outputString contains:
Output of several data types to an ostringstream object:
double:123.457
int:22
address of int:0012FE94
after additional stream insertions,
outputString contains:
Output of several data types to an ostringstream object:
double:123.457
int:22
address of int:0012FE94
more characters added

Translate »