KnowledgeBoat Logo

Computer Science

Write a program in Java to accept a string and display the new string after reversing the characters of each word.

Sample Input:
Understanding Computer Science

Sample output:
gnidnatsrednU retupmoC ecneicS

Java

Java String Handling

46 Likes

Answer

import java.util.*;

public class KboatReverse
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a string:");
        String str = in.nextLine();
        int len = str.length();
        String revStr = ""; //Empty String
        
        StringTokenizer st = new StringTokenizer(str);
        while (st.hasMoreTokens()) {
            String word = st.nextToken();
            int wordLen = word.length();
            for (int i = wordLen - 1; i >= 0; i--) {
                revStr += word.charAt(i);
            }
            revStr += " ";
        }
        
        System.out.println("String with words reversed:");
        System.out.println(revStr);
    }
}

Output

BlueJ output of Write a program in Java to accept a string and display the new string after reversing the characters of each word. Sample Input: Understanding Computer Science Sample output: gnidnatsrednU retupmoC ecneicS

Answered By

15 Likes


Related Questions