Question:
How to Reverse words in a given string?

Summary:

In the below codes we will reverse the string without reversing its individual words. Words are separated by dots.


Solution:

class Solution 

{

    //Function to reverse words in a given string.

    String reverseWords(String S)

    {

        String[] arrStr=S.split("\\.");

        StringBuilder result=new StringBuilder();

        for(int i=arrStr.length-1;i>0;i--){

            result.append(arrStr[i]).append(".");

        }

        result.append(arrStr[0]);

        return result.toString();

    }

}


Code Explanation:

Step 1: A class named Solution is defined.

Step 2: The class has a method “reverseWords” that reverses the order of words in a given string.

Step 3: The input string is split into an array of strings using dots as delimiters.

Step 4: A StringBuilder is initialized to build the reversed string.

Step 5: A loop iterates through the array of split strings in reverse order.

Each string is appended to the StringBuilder followed by a dot.

Step 6: After the loop, the first element of the original array is appended without a trailing dot.


The reversed string is obtained using result.toString() and returned by the method.


Answered by: >abhirahul

Credit: >GeekforGeeks


Suggested blogs:

>What is meant by progressive framework?

>Why logged user object is all strings in Vuejs and Laravel 10?

>How to get the date and time and display it in a defineProps in Vuejs?

>Fix error while retrieving pages from a pdf using convert_from_path (pdf2image)

>How .transform handle the splitted groups?

>Can I use VS Code's launch config to run a specific python file?

>Python: How to implement plain text to HTML converter?

>How to write specific dictionary list for each cycle of loop?

>Reading a shapefile from Azure Blob Storage and Azure Databricks


Submit
0 Answers

What Our Clients Say About Us

Client satisfaction is our ultimate goal. Here are some kind words of our precious clients they have used to express their satisfaction with our service.

Why Choose Us ?

We endow businesses with flexible engagement models based on their unique needs. Our strength lies in state-of-the-art technology and affordable consulting services. Try us for fast POCs, full-fledged applications, or technology consulting. Always available for your service.