Learn-dsa..in 30 days!



























CC-5 : Reverse each word’s characters.

Description:

Given input String containing words, reverse the letters of the words of the String.

Test cases and expected outputs:

Input Parameters Expected outputs
str="Java is the best"; avaJ si eht tseb
str=" Data structures and algorithms using Java "; ataD serutcurts dna smhtirogla gnisu avaJ

Pseudocode:

The java method should accept following input parameters: str (String).
Extract the characters from str into char array names chars.
Set value of str to a blank string. We will use reinitialized str to assemble the reversed string.
Declare a String variable word, we will use this to store individual word we find in the chars array.
Iterate through chars using for loop using idx as loop variable, starting from index 0 and incrementing idx till we reach chars.length-1:
If chars[idx] is not equal to a space, we will add chars[idx] to word, this way we will start assembling a word from the characters. Using this code word=chars[idx]+word will reverse the order of characters in the word.
If chars[idx] is equal to space, it means we have found a new word:  Do str=str+word, this will append word to reconstructed str.  Reset word to “”, so that we can start assembling the next word.
After above loop is completed, letters of words in str have been reversed. Return str.

Code:

public String stringReverseEachWordsChars(String str) {
	String word=""; 
	char[] chars=str.toCharArray();
	str="";
	for (int idx=0; idx < chars.length; idx++) {
		if (chars[idx] != ' ') {
			word=chars[idx]+word;
			
		} else {
			if (word.length() !=0) {
			if (str.length() !=0) {str=str+" ";}
			str=str+word;
			word="";
			}
		}	
	}	
	if (word.length() !=0) {
		str=str+" "+word;
	}
	return str;
}

Click here to download and run code and test cases !