c ++查找字符串
Program 1:
程序1:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "string 1";
string s2 = "string 2";
string s3;
s3 = s1 + "-" + s2;
cout << s3 << endl;
return 0;
}
Output:
输出:
string 1-string 2
Explanation:
说明:
Here, we used string class, which is present in <string> header file. We created three objects s1, s2, and s3. s1 and s2 initialized with "string1 " and "string 2" respectively. Here '+' operator is overloaded to concatenate strings. Here we concatenate s1, "-", and s2 using '+' operator and assigned the final string to the s3 object, and then we print s3 on the console screen.
在这里,我们使用了字符串类,该类存在于<string>头文件中。 我们创建了三个对象s1 , s2和s3 。 s1和s2分别用“ string1”和“ string2”初始化。 在这里,“ +”运算符被重载以连接字符串。 在这里,我们使用“ +”运算符将s1 ,“-”和s2连接起来,并将最终字符串分配给s3对象,然后在控制台屏幕上打印s3 。
Program 2:
程式2:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "string 1";
char s2[] = "string 2";
string s3;
s3 = s1 + "-" + s2;
cout << s3 << endl;
return 0;
}
Output:
输出:
string 1-string 2
Explanation:
说明:
Here, we used string class, which is present in <string> header file. We created two objects s1 and s3. Here s2 is the character array. s1 and s2 initialized with "string1 " and "string 2" respectively. Here '+' operator is overloaded to concatenate strings as well as the character array. Here we concatenate s1, "-", and s2 using '+' operator and assigned the final string to the s3 object, and then we print s3 on the console screen.
在这里,我们使用了字符串类,该类存在于<string>头文件中。 我们创建了两个对象s1和s3 。 这里s2是字符数组。 s1和s2分别用“ string1”和“ string2”初始化。 在这里,“ +”运算符被重载以连接字符串以及字符数组。 在这里,我们使用“ +”运算符将s1 ,“-”和s2连接起来,并将最终字符串分配给s3对象,然后在控制台屏幕上打印s3 。
Program 3:
程式3:
#include <iostream>
#include <string>
using namespace std;
int main()
{
char s1[] = "string 1";
char s2[] = "string 2";
string s3;
s3 = s1 + "-" + s2;
cout << s3 << endl;
return 0;
}
Output:
输出:
main.cpp: In function ‘int main()’:
main.cpp:11:13: error: invalid operands of types ‘char [9]’
and ‘const char [2]’ to binary ‘operator+’
s3 = s1 + "-" + s2;
~~~^~~~~
Explanation:
说明:
Here, we are trying to concatenate two character arrays using '+' operator. But '+' operator cannot concatenate two characters array. If we used any one of string object then '+' operator can be used for concatenation. That's why the above program will generate a compilation array.
在这里,我们试图使用'+'运算符来连接两个字符数组。 但是'+'运算符不能连接两个字符数组。 如果我们使用任何一个字符串对象,则可以使用'+'运算符进行串联。 这就是上面的程序将生成一个编译数组的原因。
翻译自: https://www.includehelp.com/cpp-tutorial/strings-find-output-programs-set-1.aspx
c ++查找字符串