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