Write a Java Program to Swap first and last character of words in a Sentence as mentioned in the example? Examples:
Input : geeks for geeks
Output :seekg rof seekg
Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is.
- First we will create an Char array of given String by using toCharArray() method.
- Now we iterate the char array by using for loop.
- In for loop, we declare a variable whose value is dependent on i.
- Whenever we found an alphabet we increase the value of i and whenever we reach at space, we are going to perform swapping between first and last character of the word which is previous of space.
Implementation:
JAVA
class SwapFirstLastCharacters {
static String count(String str)
{
char [] ch = str.toCharArray();
for ( int i = 0 ; i < ch.length; i++) {
int k = i;
while (i < ch.length && ch[i] != ' ' )
i++;
char temp = ch[k];
ch[k] = ch[i - 1 ];
ch[i - 1 ] = temp;
}
return new String(ch);
}
public static void main(String[] args)
{
String str = "geeks for geeks" ;
System.out.println(count(str));
}
}
|
Time complexity: O(n) where n is the length of the given input string
Auxiliary space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!