Given string str, the task is to print the last character of each word in the string.
Examples:
Input: str = “Geeks for Geeks” Output: s r s Input: str = “computer applications” Output: r s
Approach: Append an area i.e. ” “ at the top of the given string in order that the last word within the string is additionally followed by an area a bit like all the opposite words within the string. Now start traversing the string character by character, and print every character which is followed by an area .
Below is that the implementation of the above approach:
// Java implementation of the approach class GFG { // Function to print the last character // of each word in the given string static void printLastChar(String str) { // Now, last word is also followed by a space str = str + " "; for (int i = 1; i < str.length(); i++) { // If current character is a space if (str.charAt(i) == ' ') // Then previous character must be // the last character of some word System.out.print(str.charAt(i - 1) + " "); } } // Driver code public static void main(String s[]) { String str = "Geeks for Geeks"; printLastChar(str); } }
Output:
s r s