C++/String/string copy
Содержание
Copy char array from a string to a char pointer
#include <iostream>
using std::cout;
using std::endl;
#include <string>
using std::string;
int main()
{
string string1( "STRINGS" );
int length = string1.length();
char *ptr2 = new char[ length + 1 ];
string1.copy( ptr2, length, 0 );
ptr2[ length ] = "\0";
cout << "\nptr2 is " << ptr2 << endl;
delete [] ptr2;
return 0;
}
/*
ptr2 is STRINGS
*/
Copying Strings
#include <iostream>
#include <string>
using namespace std;
int main( )
{
string s1( "this is a test" );
string s1_copy;
s1_copy = s1;
string s1_duplicate( s1 );
cout << "String 1: " << s1
<< "\nCopy of String 1: " << s1_copy
<< "\nDuplicate of String1: " << s1_duplicate;
string s2( "B" );
cout << "\n\nString 2: " << s2;
s1 = s2.substr( 0, 6 );
cout << s1;
}
Initializing, Assigning (Copying), and Concatenating Strings Using std::string
#include <string>
#include <iostream>
int main ()
{
std::string str1 ("This is a C++ string! ");
std::cout << "str1 = " << str1 << std::endl;
std::string str2;
str2 = str1;
std::cout << "Result of assignment, str2 = " << str2 << std::endl;
str2 = "Hello string!";
std::cout << "After over-writing contents, str2 = " << str2;
std::string strAddResult = str1 + str2;
std::cout << strAddResult;
return 0;
}
STL string Instantiation and Copy Techniques
#include <string>
#include <iostream>
using namespace std;
int main ()
{
const char* pChar = "Hello String!";
cout << pChar << endl;
std::string strFromConst (pChar);
cout << strFromConst << endl;
std::string str2 ("Hello String!");
std::string str2Copy (str2);
cout << str2Copy << endl;
// Initialize a string to the first 5 characters of another
std::string subString (pChar, 5);
cout << subString << endl;
return 0;
}