Swap corner words and reverse middle characters
Last Updated :
09 Jun, 2022
Write a Java program to take an input string and exchange the first and last word and reverse the middle word.
Examples:
Input : Hello World GFG Welcomes You
Output :You semocleW GFG dlroW Hello
Approach:
- First we take two empty Strings and first String take the first word and second String takes the last word
- When we iterate each word, then we must take care about the variable pointing to next word apart from the last word.
- Now we reverse the left String in the given String.
- After the above process, we first print last word and reverse of left Strings and after that the first word.
C++
#include <iostream>
using namespace std;
void print(string s)
{
string fst = "" ;
int i = 0;
for (i = 0; i < s.length();) {
while (s[i] != ' ' ) {
fst = fst + s[i];
i++;
}
break ;
}
string last = "" ;
int j = 0;
for (j = s.length() - 1; j >= i;) {
while (s[j] != ' ' ) {
last = s[j] + last;
j--;
}
break ;
}
cout<<last;
for ( int m = j; m >= i; m--) {
cout<<s[m];
}
cout<<fst;
}
int main() {
string s = "Hello World GFG Welcomes You" ;
print(s);
return 0;
}
|
Java
public class ExchangeFirstLastReverseMiddle {
static void print(String s)
{
String fst = "" ;
int i = 0 ;
for (i = 0 ; i < s.length();) {
while (s.charAt(i) != ' ' ) {
fst = fst + s.charAt(i);
i++;
}
break ;
}
String last = "" ;
int j = 0 ;
for (j = s.length() - 1 ; j >= i;) {
while (s.charAt(j) != ' ' ) {
last = s.charAt(j) + last;
j--;
}
break ;
}
System.out.print(last);
for ( int m = j; m >= i; m--) {
System.out.print(s.charAt(m));
}
System.out.println(fst);
}
public static void main(String[] args)
{
String s = "Hello World GFG Welcomes You" ;
print(s);
}
}
|
Python3
def Print (s) :
fst = ""
i = 0
while (i < len (s)) :
while (s[i] ! = ' ' ) :
fst = fst + s[i]
i + = 1
break
last = ""
j = len (s) - 1
while (j > = i) :
while (s[j] ! = ' ' ) :
last = s[j] + last
j - = 1
break
print (last, end = "")
m = j
while m > = i :
print (s[m] , end = "")
m - = 1
print (fst, end = "")
s = "Hello World GFG Welcomes You"
Print (s)
|
C#
using System;
class ExchangeFirstLastReverseMiddle
{
static void print( string s)
{
string fst = "" ;
int i = 0;
for (i = 0; i < s.Length;) {
while (s[i] != ' ' )
{
fst = fst + s[i];
i++;
}
break ;
}
string last = "" ;
int j = 0;
for (j = s.Length - 1; j >= i;) {
while (s[j] != ' ' ) {
last = s[j] + last;
j--;
}
break ;
}
Console.Write(last);
for ( int m = j; m >= i; m--) {
Console.Write(s[m]);
}
Console.Write(fst);
}
public static void Main()
{
string s = "Hello World GFG Welcomes You" ;
print(s);
}
}
|
Output:
You semocleW GFG dlroW Hello
Time Complexity: O(N2) where N is the length of the string
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...