Friday, May 3, 2024
HomejQuery3 Methods to Concatenate String in C++ with 4 Examples

3 Methods to Concatenate String in C++ with 4 Examples


Easy methods to Concatenate String in C++

With a purpose to concatenate or mix two or extra strings in C++, it’s possible you’ll use other ways. These embrace:

  • Utilizing + operator
  • A predefined library perform append()
  • Through the use of strcat() perform

The next part reveals examples for every of the above talked about methods.

Utilizing ‘+’ operator to mix strings in C++

Utilizing ‘+’ operator is only a matter of utilizing a + arithmetic operator that returns two or extra given strings mixed.

An instance of mixing two strings:



Output:

CPP-concat

Concatenating three strings by ‘+’ operator instance



Output:

You may see within the first instance, we mixed two strings and within the second C++ program, we mixed three strings by utilizing the ‘+’ operator.

Second means: utilizing append() perform instance

Following is the syntax of utilizing the append() perform to mix strings:

Str1.append(Str2);

Which means, the append perform takes a string as a parameter. This string is added to the top of one other string object.

The instance beneath reveals the append perform utilization:



Output:

CPP-concat-append

Third means of concatenation – Utilizing strcat() perform

You may as well use strcat() to concatenate two strings simply. Following is the syntax:

char* strcat( char* dest, const char* src );

  • It takes two parameters (char arrays)
  • The src parameter is appended to the dest
  • This perform returns the dest. pointer to the vacation spot string.
  • Outlined within the <cstring> header file

See a C++ program for strcat() utilization:



Output:

CPP-strcat


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments