C++ Strings | Find output programs | Set 1

This section contains the C++ find output programs with their explanations on C++ Strings (set 1).
Submitted by Nidhi, on July 16, 2020

Program 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.

Program 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.

Program 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.







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.