Friday, 25 October 2013

String Class



In the C++ programming language, the std::string class is a standard representation for a string of text. This class reduces many of the problems introduced by C-style strings by putting the responsibility of memory ownership on the string class rather than on the programmer. The class provides some typical string operations like comparison, concatenation, find and replace, and a function for obtaining sub-strings It can be constructed from a C-style string, and a C-style string can also be obtained from it. Here is an example C-program


C++ Program :


 #include <iostream>  
 #include <string>  
 using namespace std;  
 int main ()  
 {  
  string str ("Test string");// you can also input string from user using cin  
  string str1 = "abcd";  
  string str2 = "efgh adnjka";   // or like this   
   if(str1!=str2)          // direct comparison  
   cout<<"\n Its different \n";   
   cout<<"\n"<<str1 + " " + str2<<"\n "; //concatenation  
  for (int i=0; i<str.length(); ++i)  
  {  
   cout << str[i];             //character by character  
  }  
  cout<<"\n"<<str;            //whole string   
 }  

And here is the output


No comments:

Post a Comment

THANKS FOR UR GREAT COMMENT

Blogger Widgets