同一部分,完全以代码形式作解
#include<string>
#include<iostream>
using namespace std;
int main(){
string str= "hello ";
const char *c = "RALPHFJY ";
str.append(c);
cout<<str<<endl;
const char*ch = "and FUNKYA blablabla";
str.append(ch,10);
cout<<str<<endl;
string str1 = " and ";
string str2 = "forever";
str.append(str1);
str+=str2;
cout<<str<<endl;
string str3 = "@@@!#";
str.append(str3.begin()+3,str3.begin()+4);
cout<<str<<endl;
str.append(7,'h');
cout<<str<<endl;
}
//append的用法
#include<string>
#include<iostream>
using namespace std;
int main(){
string str1 ="hello";
string str2 = "world";
str1.swap(str2);
cout<<str1<<endl;
cout<<str2<<endl;
}
#include <iostream> // std::cout
#include <string> // std::string
int main ()
{
std::string str ("There are two needles in this haystack with needles.");
std::string str2 ("needle");
// different member versions of find in the same order as above:
std::size_t found = str.find(str2);
if (found!=std::string::npos)
std::cout << "first 'needle' found at: " << found << '\n';
found=str.find("needles are small",found+1,6);
if (found!=std::string::npos)
std::cout << "second 'needle' found at: " << found << '\n';
found=str.find("haystack");
if (found!=std::string::npos)
std::cout << "'haystack' also found at: " << found << '\n';
found=str.find('.');
if (found!=std::string::npos)
std::cout << "Period found at: " << found << '\n';
// let's replace the first needle:
str.replace(str.find(str2),str2.length(),"preposition"); //replace 用法
std::cout << str << '\n';
return 0;
}
第三处代码来源于网络上的例子
#include<iostream>
#include<string>
using namespace std;
int main(){
string str ="-45";
int signal = stoi(str);
cout<<signal<<endl;
string str2 = "-1.234";
double signal2 = stof(str2);
cout<<signal2+3<<endl;
int num = 123;
string str3 = to_string(num);
cout<<str3[1]<<endl;
}