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 a space i.e. ” “ at the end of the given string so that the last word in the string is also followed by a space just like all the other words in the string. Now start traversing the string character by character, and print every character which is followed by a space.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printLastChar(string str)
{
str = str + " " ;
for ( int i = 1; i < str.length(); i++) {
if (str[i] == ' ' )
cout << str[i - 1] << " " ;
}
}
int main()
{
string str = "Geeks for Geeks" ;
printLastChar(str);
}
|
Java
class GFG {
static void printLastChar(String str)
{
str = str + " " ;
for ( int i = 1 ; i < str.length(); i++) {
if (str.charAt(i) == ' ' )
System.out.print(str.charAt(i - 1 ) + " " );
}
}
public static void main(String s[])
{
String str = "Geeks for Geeks" ;
printLastChar(str);
}
}
|
Python3
def printLastChar(string):
string = string + " "
for i in range ( len (string)):
if string[i] = = ' ' :
print (string[i - 1 ], end = " " )
string = "Geeks for Geeks"
printLastChar(string)
|
C#
using System;
class GFG
{
static void printLastChar( string str)
{
str = str + " " ;
for ( int i = 1; i < str.Length; i++)
{
if (str[i] == ' ' )
Console.Write(str[i - 1] + " " );
}
}
public static void Main()
{
string str = "Geeks for Geeks" ;
printLastChar(str);
}
}
|
PHP
<?php
function printLastChar( $str )
{
$str = $str . " " ;
for ( $i = 1; $i < strlen ( $str ); $i ++)
{
if (! strcmp ( $str [ $i ], ' ' ))
echo ( $str [ $i - 1] . " " );
}
}
$str = "Geeks for Geeks" ;
printLastChar( $str );
?>
|
Javascript
<script>
function printLastChar(str) {
str = str + " " ;
for ( var i = 1; i < str.length; i++) {
if (str[i] === " " )
document.write(str[i - 1] + " " );
}
}
var str = "Geeks for Geeks" ;
printLastChar(str);
</script>
|
Time complexity: O(n) where n is the length of the given string.
Auxiliary space: O(1)