C++ 字符串拼接

第一种方法直接是字符串之间相加

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1+s2; 
   cout <<s3 <<endl;
}

第二种方法使用append

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1.append(s2); 
   cout <<s3 <<endl;
}

append 可以设置参数 

例如 append(“s1”,3) 这就是把s1前三位拼接

例如下面的就是把adbc的前2位,也就是ab 拼接到s1 上面

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1.append("abcd",2); 
   cout <<s3 <<endl;
}

打印结果 

 append(s1,2,4)设置2个参数,就是从第2位开始后面的四位拼接

下面的就是abcdefg从第二位开始后面四位拼接到s1上面

#include <iostream>
using namespace std;
#include <string>
int main()
{
   string s1 ="hello ";
   string s2 = "world";
   string s3 = s1.append("abcdefg",2,4); 
   cout <<s3 <<endl;
}

猜你喜欢

转载自blog.csdn.net/qq_33210042/article/details/131225857