Remove the first and last character of each word in a string
Last Updated :
25 Sep, 2022
Given the string the task is to remove the first and last character of each word in a string.
Examples:
Input: Geeks for geeks
Output: eek o eek
Input: Geeksforgeeks is best
Output: eeksforgeek es
Approach :
- Split the String based on the space
- Run a loop from the first letter to the last letter.
- Check if the character is the starting or end of the word
- Remove this character from the String.
Below is the implementation of the above approach.
C++
#include<bits/stdc++.h>
using namespace std;
string FirstAndLast(string str)
{
str+= " " ;
string res= "" ,w= "" ;
for ( int i=0;i<str.length();i++)
{
if (str[i]== ' ' )
{
res +=w.substr(1,w.length()-2)+ " " ;
w= "" ;
}
else
{
w+=str[i];
}
}
return res;
}
int main()
{
string str = "Geeks for Geeks" ;
cout << (str) << endl;
cout << FirstAndLast(str) << endl;
return 0;
}
|
Java
import java.util.*;
class GFG {
static String FirstAndLast(String str)
{
String[] arrOfStr = str.split( " " );
String res = "" ;
for (String a : arrOfStr) {
res += a.substring( 1 , a.length() - 1 ) + " " ;
}
return res;
}
public static void main(String args[])
{
String str = "Geeks for Geeks" ;
System.out.println(str);
System.out.println(FirstAndLast(str));
}
}
|
Python3
def FirstAndLast(string) :
arrOfStr = string.split();
res = "";
for a in arrOfStr :
res + = a[ 1 : len (a) - 1 ] + " " ;
return res;
if __name__ = = "__main__" :
string = "Geeks for Geeks" ;
print (string);
print (FirstAndLast(string));
|
C#
using System;
class GFG
{
static String FirstAndLast(String str)
{
String[] arrOfStr = str.Split( ' ' );
String res = "" ;
foreach (String a in arrOfStr)
{
res += a.Substring(1, a.Length-2) + " " ;
}
return res;
}
public static void Main(String []args)
{
String str = "Geeks for Geeks" ;
Console.WriteLine(str);
Console.WriteLine(FirstAndLast(str));
}
}
|
PHP
<?php
function FirstAndLast( $str )
{
$str .= " " ;
$res = (string) NULL;
$w = (string) NULL;
for ( $i =0; $i < strlen ( $str ); $i ++)
{
if ( $str [ $i ]== ' ' )
{
$res .= substr ( $w , 1 , strlen ( $w )-2) ;
$res .= " " ;
$w = (string) NULL;
}
else
{
$w .= $str [ $i ];
}
}
return $res ;
}
$str = "Geeks for Geeks" ;
echo $str , "\n" ;
echo FirstAndLast( $str );
?>
|
Javascript
<script>
function FirstAndLast(str) {
str += " " ;
var res = "" ,
w = "" ;
for ( var i = 0; i < str.length; i++)
{
if (str[i] === " " ) {
res += w.substring(1, w.length - 1) + " " ;
w = "" ;
} else {
w += str[i];
}
}
return res;
}
var str = "Geeks for Geeks" ;
document.write(str + "<br>" );
document.write(FirstAndLast(str) + "<br>" );
</script>
|
Output:
Geeks for Geeks
eek o eek
Time complexity: O(n) where n is the length of the given string
Auxiliary space: O(n) because using extra space for string res and string w.
Share your thoughts in the comments
Please Login to comment...