First and last character of each word in a String
Last Updated :
04 Apr, 2025
Given a string s
consisting of multiple words, print the first and last character of each word. If a word contains only one character, print it twice (since the first and last characters are the same).
Note: The string will not contain leading or trailing spaces.
Examples:
Input: s = "Geeks for geeks"
Output: Gs fr gs
Explanation: "Geeks" → "Gs", "for" → "fr", "geeks" → "gs"
Input: s = "Computer applications"
Output: Cr as
Explanation: "Computer" → "Cr", "applications" → "as"
Input: s="Code a Program"
Output: Ce aa Pm
Explanation: "Code" → "Ce", "a" → "aa", "Program" → "Pm"
[Approach 1] String Traversal - O(n) time and O(1) space
- Run a loop from the first letter to the last letter.
- Print the first and last letter of the string.
- If there is a space in the string then print the character that lies just before space and just after space.
C++
#include <iostream>
using namespace std;
void FirstAndLast(string s)
{
for (int i = 0; i < s.length(); i++)
{
// If it is the first word
// of the string then print it.
if (i == 0)
cout << s[i];
// If it is the last word of the string
// then also print it.
if (i == s.length() - 1)
cout << s[i];
// If there is a space
// print the successor and predecessor
// to space.
if (s[i] == ' ')
{
cout << s[i - 1] << " " << s[i + 1];
}
}
}
int main()
{
string s = "Geeks for geeks";
FirstAndLast(s);
}
Java
public class GfG {
public static void firstAndLast(String s)
{
for (int i = 0; i < s.length(); i++) {
// If it is the first character of the string
if (i == 0) {
System.out.print(s.charAt(i));
}
// If it is the last character of the string
if (i == s.length() - 1) {
System.out.print(s.charAt(i));
}
// If there is a space, print the predecessor
// and successor
if (s.charAt(i) == ' ') {
System.out.print(s.charAt(i - 1));
System.out.print(" ");
System.out.print(s.charAt(i + 1));
}
}
}
public static void main(String[] args)
{
String s = "Geeks for geeks";
firstAndLast(s);
}
}
Python
def FirstAndLast(s):
# Split the string into words by spaces
words = s.split()
for word in words:
# Print the first and last character of each word
if len(word) == 1:
# If the word is a single character, print it twice
print(word[0], end=' ')
else:
# Print first and last character
print(word[0] + word[-1], end=' ')
s = "Geeks for geeks"
FirstAndLast(s)
C#
using System;
class GfG
{
static void FirstAndLast(string s)
{
for (int i = 0; i < s.Length; i++)
{
// If it is the first character of the string
if (i == 0)
Console.Write(s[i]);
// If it is the last character of the string
if (i == s.Length - 1)
Console.Write(s[i]);
// If there is a space, print the predecessor and successor
if (s[i] == ' ')
{
Console.Write(s[i - 1]);
Console.Write(" ");
Console.Write(s[i + 1]);
}
}
}
static void Main()
{
string s = "Geeks for geeks";
FirstAndLast(s);
}
}
JavaScript
function FirstAndLast(s)
{
// Split the string into words
let words = s.split(" ");
// Loop through each word
for (let i = 0; i < words.length; i++) {
let word = words[i];
// If the word has only one character, print it
// twice
if (word.length === 1) {
process.stdout.write(word + " ");
}
else {
// Print the first and last character of the
// word
process.stdout.write(
word[0] + word[word.length - 1] + " ");
}
}
}
let s = "Geeks for geeks";
FirstAndLast(s);
Time Complexity: O(n)
Auxiliary Space: O(1)
[Approach 2]Using Built-in Functions - O(n) time and O(1) space
- Use stream-based functions (like
stringstream
in C++) to separate the string into words. - For each word, print its first and last character. If a word contains only one character, print it twice (as both the first and last character).
C++
#include <iostream>
#include <sstream>
using namespace std;
void FirstAndLast(string s)
{
// Split the string into words using stringstream
stringstream ss(s);
string word;
while (ss >> word)
{
// Print the first and last character of the word
cout << word[0] << word[word.length() - 1] << " ";
}
}
int main()
{
string s = "Geeks for geeks";
FirstAndLast(s);
}
Java
import java.util.StringTokenizer;
public class Main {
public static void FirstAndLast(String s)
{
// Split the string into words using StringTokenizer
StringTokenizer st = new StringTokenizer(s);
while (st.hasMoreTokens()) {
String word = st.nextToken();
// Print the first and last character of the
// word
System.out.print(
word.charAt(0) + ""
+ word.charAt(word.length() - 1) + " ");
}
}
public static void main(String[] args)
{
String s = "Geeks for geeks";
FirstAndLast(s);
}
}
Python
def FirstAndLast(s):
# Split the string into words
words = s.split()
for word in words:
# Print the first and last character of the word
print(word[0] + word[-1], end=' ')
s = "Geeks for geeks"
FirstAndLast(s)
C#
using System;
using System.Linq;
class Program {
static void FirstAndLast(string s)
{
// Split the string into words
string[] words = s.Split(' ');
foreach(string word in words)
{
// Print the first and last character of the
// word
Console.Write(word[0] + ""
+ word[word.Length - 1] + " ");
}
}
static void Main()
{
string s = "Geeks for geeks";
FirstAndLast(s);
}
}
JavaScript
function FirstAndLast(s)
{
// Split the string into words
const words = s.split(" ");
words.forEach(word => {
// Print the first and last character of the word
process.stdout.write(word[0] + word[word.length - 1]
+ " ");
});
}
const s = "Geeks for geeks";
FirstAndLast(s);
Time Complexity: O(n)
Space Complexity: O(1)
Similar Reads
Print the first and last character of each word in a String Given a string s consisting of multiple words, print the first and last character of each word. If a word contains only one character, print it twice (since the first and last characters are the same).Note: The string will not contain leading or trailing spaces.Examples: Input: s = "Geeks for geeks"
5 min read
Remove the first and last character of each word in a string Given the string the task is to remove the first and last character of each word in a string.Examples: Input: Geeks for geeksOutput: eek o eek Input: Geeksforgeeks is bestOutput: eeksforgeek es Approach : Split the String based on the spaceRun a loop from the first letter to the last letter.Check if
4 min read
Find repeated character present first in a string Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
15 min read
Length Of Last Word in a String Given a string s consisting of upper/lower-case alphabets and empty space characters ' ', return the length of the last word in the string. If the last word does not exist, return 0. Examples: Input : str = "Geeks For Geeks"Output : 5length(Geeks)= 5Input : str = "Start Coding Here"Output : 4length(
13 min read
Searching For Characters and Substring in a String in Java Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java.Searching for a Character in a
5 min read