C++ 文字列の連結

最初の方法は文字列間に直接追加する方法です。

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

2 番目の方法では、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 の最初の 3 桁を結合します。

たとえば、次の例では、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 桁目から始まる次の 4 桁の結合を設定します。

以下はabcdefgの2桁目から始まり最後の4桁を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