Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Java program to swap first and last characters of words in a sentence
Next article icon

Java Program to Swap Corner Words and Reverse Middle Characters of a String

Last Updated : 31 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string containing n numbers of words. The task is to swap the corner words of the string and reverses all the middle characters of the string.

Input:  "Hello this is the GFG user" Output: "user GFG eth si siht Hello" Input:  "Hello Bye" Output: "Bye Hello"

Methods:

  1. Using the concept of ASCII values
  2. Using the split() method

Method 1: Using the concept of ASCII values  

We handle the position of space between the words using ASCII values. The ASCII value of space is 32.

  1. Create two string variables and two pointers lets name as index and index1
  2. Iterate the first loop using the index address variable till the first space and store all the characters in a string variable named First.
  3. Iterate another loop from reverse order using the index1 address variable till the first space and store all the characters in another string variable name as last.
  4. Now, we have the address variables index1 and index that both point to the next starting and ending position of the middle characters of the given string.
  5. Using both pointers store all the characters in reverse order in a third-string variable named as middle.
  6. Print the last string then the middle string then the first string.

Example:

Java
// Java Program to Swap Corner Words and Reverse Middle // Characters  // Importing utility classes import java.util.*; // Importing input output classes  import java.io.*;  // Main class public class GFG {      // Method 1     // To swap corners words     static void swap(String m, int length)     {          // Declaring string variables to         // store the first and last characters         String first = "";         String last = "";          // Creating first address variable         // Initially initializing with zero         int index = 0;          for (index = 0; index < length; ++index) {              // Checking the space             if (m.charAt(index) == 32) {                 break;             }              // Storing the last word in the last variable             last += m.charAt(index);         }          // Now creating second address variable         // Initially initializing with zero         int index1 = 0;          for (index1 = length - 1; index1 >= 0; --index1) {             if (m.charAt(index1) == 32) {                 break;             }              // Storing the First word of the given string             first = m.charAt(index1) + first;         }          String middle = "";         for (int i = index1 - 1; i > index; --i) {             if (m.charAt(i) == 32) {                 middle += " ";             }             else {                  // Storing all the middle words                 middle += m.charAt(i);             }         }          // Print and display all the string variables         System.out.print(first + " " + middle + " " + last);     }      // Method 2     // Main driver method     public static void main(String[] args)     {         // Given custom input string         String m = "Hello this is the GFG";          // Calculating string length using length() method         // and storing it in a variable         int length = m.length();          // Calling the method 1 to swap the words         // for our custom input string         swap(m, length);     } } 

Output
GFG eht si siht Hello

Time Complexity: O(n) where n is the length of the string

Auxiliary Space: O(1)

Method 2: Using the split() method 

The string split() method breaks a given string around matches of the given regular expression.

Illustration:

Input        : 016-78967 Processing    : Regular Expression                                Output       : {"016", "78967"}

Procedure: 

  • Store all the words in an array using split() method.
  • Swap the last and first element of the array.
  • Iterate the loop from the second position to the last second position.
  • Store all the characters in the reverse order name as the middle variable.
  • Print the first element of the array then the middle variable then the last element of the array.

Example: 

Java
// Java Program to Swap Corner Words and Reverse Middle // Characters  // Importing utility classes // Importing input output classes import java.io.*; import java.util.*;  // Main class public class GFG {      // Method 1     // To swap the words in a string     static void swap(String m, int length)     {         // Storing the words in the array         String msg[] = m.split(" ");          // Now swap the position of the first and the last         // character in the string array         String temp = msg[0];         msg[0] = msg[msg.length - 1];         msg[msg.length - 1] = temp;          // Declaring and initializing string for         // middle string empty middle string         String mid = "";          for (int i = msg.length - 2; i >= 1; --i) {             String temp_s = msg[i];              // Now storing the middle words in reverse order             for (int j = temp_s.length() - 1; j >= 0; --j) {                 mid += temp_s.charAt(j);             }             mid += " ";         }          // Lastly print the swapped and reversed words         System.out.print(msg[0] + " " + mid + " "                          + msg[msg.length - 1]);     }      // Method 2     // Main driver method     public static void main(String[] args)     {         // Custom input string         String m = "Hello this is the GFG";          // Calculating length using length() method and         // storing it         int length = m.length();          // Calling the method 1 over custom input string to         // get swapped corner words with reverse middle         // characters         swap(m, length);     } } 

Output
GFG eht si siht  Hello

Time Complexity: O(n) where n is the length of the string

Auxiliary Space: O(n) where n is the length of the string


Next Article
Java program to swap first and last characters of words in a sentence
author
zack_aayush
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-String-Programs
Practice Tags :
  • Java

Similar Reads

  • Java program to swap first and last characters of words in a sentence
    Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples: Input : geeks for geeks Output :seekg rof seekg Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is. First
    2 min read
  • Swap corner words and reverse middle characters
    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 th
    5 min read
  • Java Program to Swap characters in a String
    The task at hand involves manipulating a string S of length N, given as input. The string is subjected to a series of B swaps, each performed according to the following procedure: The character at position i is swapped with the character located C positions ahead of it, or (i + C)%N. This swapping p
    6 min read
  • Java Program to Replace Multiple Characters in a String
    In this program, we will be discussing various methods for replacing multiple characters in String. This can be done using the methods listed below: Using String.replace() methodUsing replaceAll() method Using replaceFirst() method Method 1: Using String.replace() method This method returns a new st
    3 min read
  • Java Program To Reverse Words In A Given String
    Example: Let the input string be "i like this program very much". The function should change the string to "much very program this like i" Examples: Input: s = "geeks quiz practice code" Output: s = "code practice quiz geeks" Input: s = "getting good at coding needs a lot of practice" Output: s = "p
    4 min read
  • Java Program to Add Characters to a String
    We will be discussing out how to add character to a string at particular position in a string in java. It can be interpreted as follows as depicted in the illustration what we are trying to do which is as follows: Illustration: Input: Input custom string = HelloOutput: --> String to be added 'Gee
    5 min read
  • Add index to characters and reverse the string
    Given a string str, the task is to encrypt and reverse the string. The string is encrypted by adding every character of the string with it's index in the string i.e. if character'a' is at index 2 then the character in the updated string will be 'a' + 2 = 'c'. Since value of string may go beyond 256,
    4 min read
  • Remove first and last character of a string in Java
    Given a string str, the task is to write the Java Program to remove the first and the last character of the string and print the modified string. Examples: Input: str = "GeeksForGeeks"Output: "eeksForGeek"Explanation: The first and last characters of the given string are 'G' and 's' respectively. Af
    5 min read
  • Java Program to Shuffle Characters in a String Without Using Shuffle()
    Rearranging the order of characters, in a string can be done by shuffling them. Although the shuffle() method provided by Java's Collections class is handy there are situations where you might require approaches. In this article, we will explore techniques, for shuffling characters in a string witho
    3 min read
  • Java Program to Minimize characters to be changed to make the left and right rotation of a string same
    Given a string S of lowercase English alphabets, the task is to find the minimum number of characters to be changed such that the left and right rotation of the string are the same. Examples: Input: S = “abcd”Output: 2Explanation:String after the left shift: “bcda”String after the right shift: “dabc
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences