March 03, 2024

Java Problems Solutions: How to Reverse each Word in a String in Java


public class ReverseWordsInString {
    public static void main(String[] args) {
        String input = "Follow me in LinkedIn";
        String output = combineWords(input);
        System.out.println("Input: " + input);
        System.out.println("Output: " + output);
    }
	// Function to create the output String
    public static String combineWords(String str) {
        // Split the string into words
        String[] words = str.split(" ");
        StringBuilder outputString = new StringBuilder();
        // Iterate through each word
        for (String word : words) {
            // Reverse the word and append it to the result
            String reversedWord = reverseWord(word);
            outputString.append(reversedWord).append(" ");
        }
        // Convert StringBuilder to String and remove trailing space
        return outputString.toString().trim();
    }
    // Function to reverse a word
    private static String reverseWord(String word) {
        char[] wordChars = word.toCharArray();
        int start = 0;
        int end = wordChars.length - 1;
        // Swap characters from start and end until they meet in the middle
        while (start < end) {
            char temp = wordChars[start];
            wordChars[start] = wordChars[end];
            wordChars[end] = temp;
            start++;
            end--;
        }
        // Convert char array back to String
        return new String(wordChars);
    }
}

Want 1 to 1 personalized Java training? Email me at isingh30 AT gmail please. View my following video


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.