C++/String/string concatenation

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Concatenate Using STL string

  
#include <string>
#include <iostream>
int main ()
{
   using namespace std;
   string strSample1 ("Hello");
   string strSample2 (" String!");
   // Concatenate
   strSample1 += strSample2;
   cout << strSample1 << endl << endl;
   string strSample3 (" this is a test");
   strSample1.append (strSample3);
   cout << strSample1 << endl << endl;
   const char* charPointer = "another test";
   strSample1.append (charPointer);
   cout << strSample1 << endl;
   return 0;
}


Concatenating Strings

  
#include <iostream>
#include <string>
using namespace std;
int main(){
   string s1( "A " );
   string s1_original( s1 ); 
   string s2( "B " );
   cout << "String 1: " << s1 << endl << "String 2: " << s2;
   s1 += s2; 
   cout << s1;
   s1 = s1_original;
   cout << "String 1: " << s1 << "\nString 2: " << s2;
   s1 += s2.substr( 0, 18 );
   cout << s1;
}


overloaded string concatenation operator

  
 
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
   string s1( "AA" );
   string s2( " AAB" );
   string s3;
   // 
   cout << "\n\ns1 += s2 yields s1 = ";
   s1 += s2; // test overloaded concatenation
   cout << s1;
   return 0;
}
/* 

s1 += s2 yields s1 = AA AAB
 */


overloaded string concatenation operator with C-style string

  
 
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
   string s1( "AA" );
   string s2( " AAB" );
   string s3;
   // 
   cout << "\n\ns1 += \" to you\" yields" << endl;
   s1 += " to you";  
   cout << "s1 = " << s1 << "\n\n";
   return 0;
}
/* 

s1 += " to you" yields
s1 = AA to you

 */