Problem statement says that we need to reverse the each word of a given sentence.
Program :
package net.jubiliation.example;
/**
* @author Gaurav
*
*/
public class StringReverseExample {
public static void reverseWordInMyString(String sentence) {
String[] words = sentence.split(" ");
/*
* Here split() method of String class splits a string in chunks based
* on the delimiter passed as an argument to it.
*/
String reversedSentence = "";
for (int index = 0; index < words.length; index++) {
String word = words[index];
String reverseWord = "";
for (int temp = word.length() - 1; temp >= 0; temp--) {
/*
* The charAt() function returns the character at the given position in a string.
*/
reverseWord = reverseWord + word.charAt(temp);
}
reversedSentence = reversedSentence + reverseWord + " ";
}
System.out.println(sentence);
System.out.println(reversedSentence);
}
public static void main(String[] args) {
reverseWordInMyString("Welcome to jubiliation");
reverseWordInMyString("Example to reverse the words of sentence");
}
}
Result :
Welcome to jubiliation
emocleW ot noitailibuj
Example to reverse the words of sentence
elpmaxE ot esrever eht sdrow fo ecnetnes
Program :
package net.jubiliation.example;
/**
* @author Gaurav
*
*/
public class StringReverseExample {
public static void reverseWordInMyString(String sentence) {
String[] words = sentence.split(" ");
/*
* Here split() method of String class splits a string in chunks based
* on the delimiter passed as an argument to it.
*/
String reversedSentence = "";
for (int index = 0; index < words.length; index++) {
String word = words[index];
String reverseWord = "";
for (int temp = word.length() - 1; temp >= 0; temp--) {
/*
* The charAt() function returns the character at the given position in a string.
*/
reverseWord = reverseWord + word.charAt(temp);
}
reversedSentence = reversedSentence + reverseWord + " ";
}
System.out.println(sentence);
System.out.println(reversedSentence);
}
public static void main(String[] args) {
reverseWordInMyString("Welcome to jubiliation");
reverseWordInMyString("Example to reverse the words of sentence");
}
}
Result :
Welcome to jubiliation
emocleW ot noitailibuj
Example to reverse the words of sentence
elpmaxE ot esrever eht sdrow fo ecnetnes
Comments
Post a Comment