×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.