MARTIN
MARTIN

Reputation: 45

Swap the first and the last words and reverse all the middle characters

Description

Guru gave a task to his students.   He gave a sentence,  and the students have to swap the first and the last words and reverse all the characters between those words.   Help the students to solve this task using a java program.

Requirements:

Note:

Please do not use System.exit(0) to terminate the program.

Example input/output examples.  All input is preceded by the prompt Enter the sentence

Example 1:

Input: Do you wear your mask
Output: mask ruoy raew uoy Do

Example 2:

Input: Card reader
Output: Invalid Length

Example 3:

Input: Refer @ friend
Output: Refer @ friend is an invalid sentence

import java.util.Scanner;

class SentenceProcessor {
    
    // Method to check if the sentence is valid
    public boolean isValidSentence(String sentence) {
        return sentence.matches("[a-zA-Z ]+"); // Only alphabets and spaces allowed
    }

    // Method to process the sentence
    public String processSentence(String sentence) {
        if (!isValidSentence(sentence)) {
            return sentence + " is an invalid sentence";
        }

        String[] words = sentence.trim().split("\\s+"); // Split by whitespace

        if (words.length <= 2) {
            return "Invalid Length";
        }

        // Swap first and last words
        String firstWord = words[0];
        String lastWord = words[words.length - 1];
        words[0] = lastWord;
        words[words.length - 1] = firstWord;

        // Reverse middle words
        for (int i = 1; i < words.length - 1; i++) {
            words[i] = new StringBuilder(words[i]).reverse().toString();
        }

        return String.join(" ", words); // Join words with a space
    }
}

public class UserInterface {
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter the sentence");
        String input = sc.nextLine();
        
        SentenceProcessor processor = new SentenceProcessor();
        String result = processor.processSentence(input);
        
        System.out.println(result);
        
        sc.close(); // Close the scanner to avoid resource leaks
    }
}

Output:-

Enter the sentence<br>
Do you wear your mask<br>
mask uoy raew ruoy Do<br>

Expected output:-

Enter the sentence<br>
Do you wear your mask<br>
mask ruoy raew uoy Do<br>

Tried resolving this but I am failing to get desired output. I also tried using various open sources which were not able to give me correct code. They are repetitively giving me same output(like chatgpt, copilot).

Upvotes: 4

Views: 180

Answers (4)

SedJ601
SedJ601

Reputation: 13859

I originally thought your requirements didn't match one of your expected outputs. I was corrected in the comments.

This method reverses the order of the words in an array and then reverses each word, excluding the first and last words.

// Method to process the sentence
static public String processSentence(String sentence) {
    if (!isValidSentence(sentence)) {
        return sentence + " is an invalid sentence";
    }

    String[] words = sentence.trim().split("\\s+"); // Split by whitespace

    if (words.length <= 2) {
        return "Invalid Length";
    }

    //Swap all words
    String[] reverseWords = new String[words.length];
    for(int i = words.length - 1; i >= 0; i--)
    {
        reverseWords[(reverseWords.length - 1) - i] = words[i];
    }

    // Reverse middle words
    for (int i = 1; i < words.length - 1; i++) {
        reverseWords[i] = new StringBuilder(reverseWords[i]).reverse().toString();
    }

    return String.join(" ", reverseWords); // Join words with a space
}

Output:

Do you wear your mask
mask ruoy raew uoy Do

Upvotes: 4

wannaBeDev
wannaBeDev

Reputation: 739

In order to get the desired result you need to swap the elemnts of your array: the second word with the second-last word, the third word with the third-last word ... and so on. Maybe it is easier to use String.substring method for the whole task instead of spliting input in to an array:

public String processSentence(String sentence) {
    if (!isValidSentence(sentence)) {
        return sentence + " is an invalid sentence";
    }

    int firstSpaceIndex = sentence.indexOf(' ');
    int lastSpaceIndex  = sentence.lastIndexOf(' ');

    String firstWord  = sentence.substring(0, firstSpaceIndex);
    String lastWord   = sentence.substring(lastSpaceIndex + 1);
    String middlePart = sentence.substring(firstSpaceIndex, lastSpaceIndex + 1);

    return lastWord + new StringBuilder(middlePart).reverse() + firstWord;
}

EDIT

To check that the input string has at least three substrings separated by spaces, i.e that words count > 2 modify your second method where you do your validation. Doing so you separate the task of processing and validating.

public boolean isValidSentence(String sentence) {
    String regex = "^[a-zA-Z]+(\\s[a-zA-Z]+){2,}$";
    return sentence.trim().matches(regex);
}

Regex Explanation: ^[a-zA-Z]+(\\s[a-zA-Z]+){2,}$

  • ^ ensures the string starts with the first substring.

  • [a-zA-Z]+ matches a sequence of letters (a substring).

  • (\\s[a-zA-Z]+) matches a space followed by another substring.

  • {2,} ensures there are at least 2 additional substrings after the first one.

  • $ ensures the entire string adheres to the pattern.

Upvotes: 4

WJS
WJS

Reputation: 40047

The problem is that you are reversing the characters of each word. But you said you are supposed to reverse all the characters between the first and last word.

Assuming the middle words are one two three.
You are doing eno owt eerht.
What you want is eerht owt eno.

So do the following:

  • Grab the substring between the first and last spaces.
  • Then reverse that middle substring
  • and append the words and the substring in proper order
// Reverse middle characters (those between first and last word)
int start = sentence.indexOf(" ") + 1;
String middle = new StringBuilder(
        sentence.substring(start, sentence.lastIndexOf(" "))).reverse()
        .toString();

return String.join(" ", lastWord, middle, firstWord); // Join sections with a space

Upvotes: 2

Marce Puente
Marce Puente

Reputation: 478

The error is here:

for (int i = 1; i < words.length - 1; i++) {
    words[i] = new StringBuilder( words[i] ).reverse().toString();
}

the problem is that you invert the order of the letters of the central words, but not the order of them, we can do it this way:

String out = lastWord + " ";
for( int i = words.length - 2; i >= 1; i -- ) {
   out += new StringBuilder( words[ i ] ).reverse().toString() + " ";
}
return out + firstWord;

Upvotes: 4

Related Questions