DEV Community

Suresh Ayyanna
Suresh Ayyanna

Posted on

3 3 1 1 1

Reverse Each word in a String

Program to Reverse each word in String

package InterviewPrograms;

import java.util.Scanner;

public class ReverseEachWord {

    // Method 01
    public static String revWordsOfString(String str) {
        // s1.Split the String with whitespace
        String[] words = str.split(" ");

        // s2. Using for each loop read each word and reverse it
        String revstr = "";
        for (String w : words) {
            String revword = "";
            for (int i = w.length() - 1; i >= 0; i--) {
                revword = revword + w.charAt(i);
            }
            revstr = revstr + revword + " ";
        }
        return revstr;
    }

//Method 02
    public static String revWordOfString(String str) {
        // s1.Split the String with Space Reg.Expression(\\s)

        String[] word = str.split(" \\s");

        String revword = "";
        for (String w : word) {
            StringBuilder sb = new StringBuilder(w);
            sb.reverse();

            revword = revword + sb.toString() + " ";
        }
        return revword;
    }

    public static void main(String[] args) {
        System.out.println("Enter the Actual String:");
        Scanner input = new Scanner(System.in);
        String actualString = input.nextLine();

        String ExpectedString = revWordsOfString(actualString);

        System.out.println("The Reverse word of each string of given String from Method 1: " + ExpectedString);
        System.out.println(
                "The Reverse word of each string of given String from Method 2:" + revWordOfString(actualString));
    }
}

Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more