c ++查找字符串_C ++字符串| 查找输出程序| 套装1

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>头文件中。 我们创建了三个对象s1s2s3s1s2分别“ 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>头文件中。 我们创建了两个对象s1s3 。 这里s2是字符数组。 s1s2分别“ 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 ++查找字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值