Interchanging first and second halves of strings
Last Updated :
01 Aug, 2022
Given two strings and . Create two new strings by exchanging the first half and second half of one of the strings with the first half and second half of the other string respectively.
Examples:
Input : fighter
warrior
Output :warhter
figrior
Input :remuneration
day
Output :dration
remuneay
In the first example, fighter is made up of two parts fig and hter. Similarly, warrior is also made up of two parts war and rior. Interchange the first part of both the strings to create two new strings warhter and figrior. Similarly, in the second example first part of remuneration which is remune is exchanged with the first part of day to create dration and remuneay.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
void swapTwoHalves(string a , string b)
{
int la = a.length();
int lb = b.length();
string c = a.substr(0, la/2) +
b.substr(lb/2, lb);
string d = b.substr(0, lb/2) +
a.substr(la/2, la);
cout << c << endl << d << endl;
}
int main()
{
string a = "remuneration" ;
string b = "day" ;
swapTwoHalves(a, b);
return 0;
}
|
Java
import java.io.*;
class ns
{
public static void swapTwoHalves(String a,
String b)
{
int la = a.length();
int lb = b.length();
String c = a.substring( 0 ,la/ 2 ) +
b.substring(lb/ 2 ,lb);
String d = b.substring( 0 ,lb/ 2 ) +
a.substring(la/ 2 ,la);
System.out.println(c + "\n" + d);
}
public static void main (String args[])
{
String a = "remuneration" ;
String b = "day" ;
swapTwoHalves(a, b);
}
}
|
Python3
def swapTwoHalves( a ,b) :
la = len (a)
lb = len (b)
c = a[ 0 :la / / 2 ] + b[lb / / 2 : lb]
d = b[ 0 : lb / / 2 ] + a[la / / 2 : la]
print ( c, "\n" , d )
a = "remuneration"
b = "day"
swapTwoHalves(a, b)
|
C#
using System;
class GFG
{
static void swapTwoHalves( string a ,
string b)
{
int la = a.Length;
int lb = b.Length;
string c = a.Substring(0, la / 2) +
b.Substring(lb / 2,
lb / 2 + 1);
string d = b.Substring(0, lb / 2) +
a.Substring(la / 2,
la / 2);
Console.Write (c + "\n" +
d + "\n" );
}
static void Main()
{
string a = "remuneration" ;
string b = "day" ;
swapTwoHalves(a, b);
}
}
|
PHP
<?php
function swapTwoHalves( $a , $b )
{
$la = strlen ( $a );
$lb = strlen ( $b );
$c = substr ( $a , 0, intval ( $la / 2)) .
substr ( $b , intval ( $lb / 2), $lb );
$d = substr ( $b , 0, intval ( $lb / 2)) .
substr ( $a , intval ( $la / 2), $la );
echo ( $c . "\n" .
$d . "\n" );
}
$a = "remuneration" ;
$b = "day" ;
swapTwoHalves( $a , $b );
?>
|
Javascript
<script>
function swapTwoHalves(a, b)
{
var la = a.length;
var lb = b.length;
var c = a.substring(0,la/2) +
b.substring(lb/2,lb);
var d = b.substring(0,lb/2) +
a.substring(la/2,la);
document.write(c + "<br>" + "\n" + d);
}
var a = "remuneration" ;
var b = "day" ;
swapTwoHalves(a, b);
</script>
|
Time Complexity: O(n), time required for substr function
Auxiliary Space: O(n)
Share your thoughts in the comments
Please Login to comment...