Concatenating Strings (combining multiple strings into one)
Last Updated :
17 Nov, 2023
Given two strings str1 and str2, the task is to concatenate these two strings.
Given two strings str1 and str2, the task is to concatenate these two strings.
Examples:
Input: str1 = “hello”, str2 = “world”
Output: helloworld
Input: str1 = “Geeks”, str2 = “World”
Output: GeeksWorld
Approach 1: Using the “+” operator
The most traditional method of concatenating strings is by using the “+” operator.
Below is the implementation of the above method:
C++
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str1 = "Geeks" ;
string str2 = "ForGeeks" ;
string result = str1 + str2;
cout << result << endl;
return 0;
}
|
Java
class GFG {
public static void main(String args[])
{
String s1 = "Geeks" ;
String s2 = "forGeeks" );
String result = s1 + s2;
System.out.println(result);
}
}
|
Python3
str1 = "Hello "
str2 = "Geek"
str3 = str1 + str2
print (str3)
|
C#
using System;
class GFG
{
public static void Main( string [] args)
{
string s1 = "Geeks" ;
string s2 = "forGeeks" ;
string result = s1 + s2;
Console.WriteLine(result);
}
}
|
Javascript
function main() {
let str1 = "Geeks" ;
let str2 = "ForGeeks" ;
let result = str1 + str2;
console.log(result);
}
main();
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach 2: Using In-built methods
Every programming language offers a built-in method as well to concatenate strings, such as:
C
|
strcat()
|
C++
|
append( )
|
Java
|
concat()
|
JavaScript
|
concat()
|
Python
|
join()
|
Below is the implementation of the above method:
C++
#include <iostream>
using namespace std;
int main()
{
string s = "Geeks" ;
string s1 = "forGeeks" ;
s.append(s1);
cout << s << endl;
return 0;
}
|
C
#include <stdio.h>
#include <string.h>
int main()
{
char s[] = "Geeks" ;
char s1[] = "forGeeks" ;
strcat (s, s1);
printf (s);
return 0;
}
|
Java
class GFG {
public static void main(String args[])
{
String s = "Geeks" ;
String s1 = "forGeeks" ;
s = s.concat(s1);
System.out.println(s);
}
}
|
Python3
s = "Geeks"
s1 = "forGeeks"
print ("".join([s, s1]))
|
C#
using System;
class Program {
static void Main() {
string s = "Geeks" ;
string s1 = "forGeeks" ;
s = string .Concat(s, s1);
Console.WriteLine(s);
}
}
|
Javascript
function concatenateStrings() {
let s = "Geeks" ;
let s1 = "forGeeks" ;
s = s.concat(s1);
console.log(s);
}
concatenateStrings();
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Share your thoughts in the comments
Please Login to comment...