I am trying to write a java program that reverses every individual word in a sentence. For example, if the sentence is "Hello World. Hello Java." , the output should be "olleH dlroW. olleH avaJ" . I am able to do the reverse but the output I am getting is "olleH .dlroW olleH .avaJ" where even the dot is getting reversed which should not happen. Can somebody help me fix it?
Thank you!!
I tried something like this:
import java.util.Scanner;
public class ReverseWords {
public static void main(String[] args) {
System.out.println("Enter a string to be reversed:");
Scanner input = new Scanner(System.in);
String reverse = "";
while(input.hasNextLine())
{
String str = input.next();
for(int i = str.length()-1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
reverse += " ";
System.out.println(reverse);
}
}
}
Expected output: olleH dlroW. olleH avaJ.
Output I am getting:
olleH
olleH .dlroW
olleH .dlroW olleH
olleH .dlroW olleH .avaJ
Here is the java 8 solution, you may need to modify replaceChar
method if you want to restrict other special characters.
public static void main(String[] args) {
String str = "Hello World. Hello Java.";
String collect = Arrays.stream(str.split("\\s+")) // split sentences into words
.map(s -> new StringBuffer(s)) // converting to StringBuffer
.map(s -> s.reverse()) // reversing the string
.map(s -> replaceChar(s)) // replace first char if it is dot
.collect(Collectors.joining(" ")); // join all the words
System.out.println(collect);
}
private static String replaceChar(StringBuffer stringBuffer) {
if(stringBuffer.charAt(0) == '.') {
stringBuffer.deleteCharAt(0);
return stringBuffer.toString() + ".";
}
return stringBuffer.toString();
}
If you want to do it in the imperative style you can modify your code as below:
String str = "Hello World. Hello Java.";
String[] tokens = str.split("\\s+");
String reverseString = "";
for (String token : tokens) {
String reverse = "";
for (int i = token.length() - 1; i >= 0; i--) {
reverse = reverse + token.charAt(i);
}
if(reverse.charAt(0) == '.') {
reverse = reverse.substring(1) + ".";
}
reverseString = reverseString + " " + reverse;
}
System.out.println(reverseString);
Changed a little in your code to handle . in words.
import java.util.Scanner;
public class HelloWorld{
public static void main(String []args){
System.out.println("Enter a string to be reversed:");
Scanner input = new Scanner(System.in);
String reverse = "";
while(input.hasNextLine())
{
String str = input.next();
if(str.contains(".")){
str = str.replace(".","");
for(int i = str.length()-1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
reverse = reverse+".";
}
else{
for(int i = str.length()-1; i >= 0; i--)
{
reverse = reverse + str.charAt(i);
}
}
reverse += " ";
System.out.println(reverse);
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.