← All resources

Write a program to input multiple sentences each terminating with “.”, “!” or “?”. Sort the words of each sentence in alphabetical order.

Write a program to input multiple sentences each terminating with “.”, “!” or “?”. Sort the words of each sentence in alphabetical order.

/* WAP to input multiple sentences each terminating with ".", "!" or "?". Sort the words of each sentence in alphabetical order. */
import java.util.*;
class Sentence
{
    int Count(String s)
    {
        s = s.trim();
        s = s + ' ';
        int i, c = 0;
        for(i = 0 ; i < s.length() ; i++)
        {
            char ch = s.charAt(i);
            if (ch == ' ')
                c++;
        }
        return c;
    }

    String Sort(String s)
    {
        String word = "", st[], tmp, r = "";
        s = s.trim();
        s = s + ' ';
        st = new String[Count(s)];
        int i, j, k = 0, l;
        l = Count(s);
        for(i = 0 ; i < s.length() ; i++)
        {
            char ch = s.charAt(i);
            if (ch != ' ')
                word = word + ch;
            else
            {
                st[k] = word;
                k++;
                word = "";
            }
        }
        for(i = 0 ; i < l ; i++)
        {
            for(j = 0 ; j < l - 1 - i ; j++)
            {
                if (st[j].compareToIgnoreCase(st[j+1]) > 0)
                {
                    tmp = st[j];
                    st[j] = st[j+1];
                    st[j+1] = tmp;
                }
            }
        }
        for(i = 0 ; i < k ; i++)
            r = r + st[i] + " ";
        return r.trim();
    }

    void main()
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a Sentence");
        String str = sc.nextLine();
        String s = str.trim();
        int i, j, l;
        l = s.length();
        if (s.charAt(l - 1) != '.' && s.charAt(l - 1) != '!' && s.charAt(l - 1) != '?')
        {
            System.out.println("Invalid Input ! Enter the sentence again.");
            s = sc.nextLine();
            s = s.trim();
        }
        s = s + ' ';
        String word = "", sentence = "", r = "";
        for(i = 0 ; i < l ; i++)
        {
            char ch = s.charAt(i);
            if (ch != '.' && ch != '?' && ch != '!')
                sentence = sentence + ch;
            else
            {
                r = r + Sort(sentence) + ch + " ";
                sentence = "";
            }
        }
        System.out.println("\n");
        System.out.println("The Modified Sentence is: " + r);
    }
}