0% found this document useful (0 votes)
51 views

STRINGS

The document describes a program that accepts a paragraph containing one or more sentences and performs operations like checking number of sentences, finding total number of words, and displaying word frequencies. It provides examples of input/output and solutions to implement the required operations.

Uploaded by

himanibansal9191
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

STRINGS

The document describes a program that accepts a paragraph containing one or more sentences and performs operations like checking number of sentences, finding total number of words, and displaying word frequencies. It provides examples of input/output and solutions to implement the required operations.

Uploaded by

himanibansal9191
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Question 1

Input a paragraph containing ‘n’ number of sentences where (1 = < n < 4). The words are to be separated with a single blank
space and are in UPPERCASE. A sentence may be terminated either with a full stop ‘.’ Or a question mark ‘?’ only. Any other
character may be ignored. Perform the following operations:
(i) Accept the number of sentences. If the number of sentences exceeds the limit, an appropriate error message must be displayed.
(ii) Find the number of words in the whole paragraph
(iii) Display the words in ascending order of their frequency. Words with same frequency may appear in any order.
Example 1
INPUT: Enter number of sentences.
1
Enter sentences.
TO BE OR NOT TO BE.
OUTPUT:
Total number of words: 6
WORD FREQUENCY
OR 1
NOT 1
TO 2
BE 2
Example 2
INPUT: Enter number of sentences
3
Enter sentences.
THIS IS A STRING PROGRAM.IS THIS EASY?YES,IT IS.
OUTPUT:
Total number of words: 11
WORD FREQUENCY
A 1
STRING 1
PROGRAM 1
EASY 1
YES 1
IT 1
THIS 2
IS 3
Example 3
INPUT : Enter number of sentences
5
OUTPUT:
INVALID ENTRY
Solution :
import java.io.*;
import java.util.*;
class Q32010
{
public static void main() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the number of sentences");
int n= Integer.parseInt(br.readLine());
if(n<1 || n >=4)
{
System.out.println("Invalid Entry");
System.exit(0);
}
System.out.println("Enter the paragraph");
String p = br.readLine();
StringTokenizer t= new StringTokenizer(p," .?");
int w= t.countTokens();
System.out.println("Total number of words"+ w);
String word[]=new String[w];
//extract the words and store in the String array
for(int i=0;i<w;i++)
word[i]=t.nextToken();
int fr[]=new int[w]; // array to store the frequency
int visited=-1;
for(int i=0;i< w-1;i++)
{
int count=1;
for(int j=i+1;j<w;j++)
{ if( word[i].equals(word[j])) // check for equality of the word
{ count++; // increment the counter
fr[j]= visited; /* store -1 in the frequency array for the corresponding equal
word so that the frequency of the same word is not calculated again */
} }
if(fr[i]!=visited)
fr[i]=count; }
// Sort the words in ascending order of their frequency using bubble sort
for(int i=0;i<w;i++)
{
for(int j=0;j<w-1-i;j++)
{
if(fr[j]>fr[j+1]) // comparing the frequency array
{ int temp1=fr[j]; // swapping the frequencies
fr[j]=fr[j+1];
fr[j+1]=temp1;
String temp2= word[j]; // swapping the words
word[j]=word[j+1];
word[j+1]=temp2;
}
}
}

System.out.println("WORD" + "\t\t" + "FREQUENCY");


for(int i=0;i<w;i++)
{
if(fr[i]!= visited) // displaying the word and frequency of the word which is not equal to
visited
System.out.println(word[i]+"\t\t" + fr[i]);
}
}}
Question 2

Write a program to accept a paragraph containing TWO sentences only. The sentences may be terminated by either
‘.’, ‘?’ or ‘!’ only. Any other character mat be ignored. The words are to be separated by a single blank space and
must be in UPPERCASE.

Perform the following tasks:

(i) Check for the validity of the accepted paragraph for the number of sentences and for the terminating
character.
(ii) Separate the two sentences form the paragraph and find the common words in the two sentences with
their frequency of occurrence in the paragraph.
(iii) Display both the sentences separately along with the common words and their frequency, in the format
given below:

Test your program for the following data and some random data:

Example 1

INPUT: IS IT RAINING? YOU MAY GET WET IF IT IS RAINING.

OUTPUT: IS IT RAINING?
YOU MAY GET WET IF IT IS RAINING.
COMMON WORDS FREQUENCY
IS 2
IT 2
RAINING 2
Example 2

INPUT: INDIA IS MY MOTHERLAND AND I AM PROUD OF MY MOTHERLAND. ALL INDIANS ARE MY


BROTHERS
AND SISTERS.

OUTPUT: INDIA IS MY MOTHERLAND AND I AM PROUD OF MY MOTHERLAND.


ALL INDIANS ARE MY BROTHERS AND SISTERS.

COMMON WORDS FREQUENCY


MY 3
AND 2
Example 3

INPUT: ARE YOU COMING? I AM GETTING LATE.

OUTPUT: ARE YOU COMING?


I AM GETTING LATE.

NO COMMON WORDS

Example 4

INPUT: AT LAST, THE TIGER WAS SAVED.

OUTPUT: INVALID INPUT


Solution :
import java.util.*;

public class CommonWords {


public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the paragraph: ");
String para = sc.nextLine();

// Tokenize the paragraph into sentences using delimiters .?! and count the number of
sentences
StringTokenizer t = new StringTokenizer(para, ".?!");
int sn = t.countTokens();

if (sn != 2) {
System.out.println("INVALID INPUT: Please enter two sentences separated by a '.', '!', or
'?'");
System.exit(0);
}

String sent[] = new String[sn];


int i;
for (i = 0; i < sn; i++)
sent[i] = t.nextToken();

// Remove the ending punctuation from each sentence


for (i = 0; i < 2; i++) {
System.out.println(sent[i]);
sent[i] = sent[i].substring(0, sent[i].length() - 1);
}

// Tokenize the sentences into words


StringTokenizer st = new StringTokenizer(sent[0]);
String words1[] = new String[st.countTokens()];
i = 0;
while (st.hasMoreTokens()) {
words1[i++] = st.nextToken();
}

st = new StringTokenizer(sent[1]);
String words2[] = new String[st.countTokens()];
i = 0;
while (st.hasMoreTokens()) {
words2[i++] = st.nextToken();
}

String commonWords[] = new String[words1.length];


int freq[] = new int[words1.length];
int commonCount = 0;
for (i = 0; i < words1.length; i++) {
boolean duplicate = false;
for (int j = 0; j < commonCount; j++) {
if (words1[i].equals(commonWords[j])) {
duplicate = true;
break;
}
}
if (!duplicate) {
int wordCount = 0;
for (int j = 0; j < words2.length; j++) {
if (words1[i].equals(words2[j]))
wordCount++;
}
if (wordCount > 0) {
// Count the frequency of the word in the first sentence
for (int j = 0; j < words1.length; j++) {
if (words1[i].equals(words1[j]))
wordCount++;
}
commonWords[commonCount] = words1[i];
freq[commonCount] = wordCount;
commonCount++;
}
}
}

// Output the common words and their frequencies


if (commonCount == 0) {
System.out.println("NO COMMON WORDS");
} else {
System.out.printf("%20s%20s\n", "Word", "Frequency");
for (int j = 0; j < commonCount; j++) {
System.out.printf("%20s%20d\n", commonWords[j], freq[j]);
}
} }}
Question 3

A Palindrome is a word that may be read the same way in either direction.

Accept a sentence in UPPER CASE which is terminated by either ” . “, ” ? ” or ” ! “.

Each word of the sentence is separated by a single blank space.

Perform the following tasks:

(a) Display the count of palindromic words in the sentence.


(b) Display the Palindromic words in the sentence.

Example of palindromic words: MADAM, ARORA, NOON

Test your program with the sample data and some random data:

Example 1

INPUT : MOM AND DAD ARE COMING AT NOON.

OUTPUT : MOM DAD NOON


NUMBER OF PALINDROMIC WORDS : 3

Example 2

INPUT : NITIN ARORA USES LIRIL SOAP.

OUTPUT : NITIN ARORA LIRIL


NUMBER OF PALINDROMIC WORDS : 3

Example 3

INPUT : HOW ARE YOU?

OUTPUT : NO PALINDROMIC WORDS


Solution :

import java.io.*;
import java.util.*;

class PalindromeChecker {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

// Method to check if a given word is a palindrome


static boolean isPalindrome(String word) {
int length = word.length();
for (int i = 0; i < length / 2; i++) {
if (word.charAt(i) != word.charAt(length - i - 1)) {
return false;
}
}
return true;
}

public static void main() throws IOException {


System.out.print("Enter a sentence in UPPER CASE terminated by '.', '?' or '!': ");
String sentence = br.readLine().toUpperCase(); // Convert input to uppercase
StringTokenizer tokenizer = new StringTokenizer(sentence, " .?!"); // Tokenize sentence

int palindromeCount = 0;
StringBuilder palindromeWords = new StringBuilder();

while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken(); // Get each word
if (isPalindrome(word)) {
palindromeCount++;
palindromeWords.append(word).append(" ");
}
}

if (palindromeCount > 0) {
System.out.println("OUTPUT: " + palindromeWords.toString().trim());
System.out.println("NUMBER OF PALINDROMIC WORDS: " + palindromeCount);
} else {
System.out.println("OUTPUT: NO PALINDROMIC WORDS");
}
}
}
Question 4
Write a program to accept a sentence which may be terminated by either ‘.’ or ‘?’ only. The words are to
be separated by a single blank space. Print an error message if the input does not terminate with ‘.’ or ‘?’.
You can assume that no word in the sentence exceeds 15 characters, so that you get a proper formatted
output.

Perform the following tasks:


(i) Convert the first letter of each word to uppercase.
(ii) Find the number of vowels and consonants in each word and display them with proper headings along
with the words.

Test your program with the following inputs.

Example 1

INPUT: Intelligence plus character is education.

OUTPUT:
Intelligence Plus Character Is Education

Word Vowels Consonants


Intelligence 5 7
Plus 1 3
Character 3 6
Is 1 1
Education 5 4

Example 2

INPUT: God is great.

OUTPUT:
God is Great

Word Vowels Consonants


God 1 2
Is 1 1
Great 2 3

Example 3

INPUT: All the best!

OUTPUT:
Invalid Input.
Solution:

import java.util.Scanner;

public class WordAnalyzer {


public static void main() {
Scanner scanner = new Scanner(System.in);

System.out.println("Enter a sentence terminated by '.' or '?' only:");


String input = scanner.nextLine();

// Check for proper termination


char lastChar = input.charAt(input.length() - 1);
if (lastChar != '.' && lastChar != '?') {
System.out.println("Invalid Input. Sentence should end with '.' or '?'");
} else {
String[] words = input.split(" ");

System.out.println("\nOUTPUT:");

// Convert first letter of each word to uppercase


for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, 1).toUpperCase() +
words[i].substring(1).toLowerCase();
System.out.print(words[i] + " ");
}

System.out.println("\n\nWord\tVowels\tConsonants");

// Calculate and display vowels and consonants for each word


for (String word : words) {
int vowels = 0;
int consonants = 0;
for (char letter : word.toCharArray()) {
if ("AEIOUaeiou".indexOf(letter) != -1) {
vowels++;
} else if (Character.isLetter(letter)) {
consonants++;
}
}
System.out.println(word + "\t\t" + vowels + "\t\t" + consonants);
}
}
}
}
Question 5

Write a program to accept a sentence which may be terminated by either ‘.’ ‘?’ or
‘!’ only. Any other character may be ignored. The words may be separated by
more than one blank space and are in UPPER CASE.

Perform the following tasks:

(a) Accept the sentence and reduce all the extra blank space between two words
to
a single blank space.
(b) Accept a word from the user which is part of the sentence along with its
position number and delete the word and display the sentence.

Test your program with the sample data and some random data:

Example 1

INPUT: A MORNING WALK IS A IS BLESSING FOR THE WHOLE DAY.

WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6

OUTPUT: A MORNING WALK IS A BLESSING FOR THE WHOLE DAY.

Example 2

INPUT: AS YOU SOW, SO SO YOU REAP.

WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4

OUTPUT: AS YOU SOW, SO YOU REAP.

Example 3

INPUT: STUDY WELL ##.

OUTPUT: INVALID INPUT.


Solution :

import java.util.*;
class RemoveWord {
public static void main () {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String s = sc.nextLine();

// Convert the input sentence to uppercase for uniformity


s = s.toUpperCase();

int l = s.length();
char last = s.charAt(l-1);

// Check if the sentence ends with '.', '?', or '!'


if(last != '.' && last != '?' && last != '!') {
System.out.println("Invalid Input. End a sentence with either '.', '?' or '!' only");
} else {
// Tokenize the sentence
StringTokenizer str = new StringTokenizer(s," .?!");
int c = str.countTokens(); // Count the number of words

String w="", ans = "";


System.out.print("Enter the word to delete: ");
String del = sc.next();

System.out.print("Enter the word position in the sentence: ");


int x = sc.nextInt();

if(x<1 || x>c) {
System.out.println("Sorry! The word position entered is out of range");
} else {
for(int i=1; i<=c; i++) {
w = str.nextToken();

// If the word matches the word to delete and is at the specified position, skip it
if(w.equals(del) && i == x)
continue;

ans = ans + w + " ";


}
// Output the modified sentence
System.out.print("Output: "+ans.trim()+last);
}
}}
Question 6.

Write a program to accept a sentence as input. The words in the string are to be
separated by a blank. Each word must be in upper case. The sentence is terminated
by either “.”,”!” or “?”. Perform the following tasks:

(i) Obtain the length of the sentence. (measured in words)

(ii) Arrange the sentence in alphabetical order of the words.

Test your program with the sample data and some random data:

Example 1:

INPUT: NECESSITY IS THE MOTHER OF INVENTION.

OUTPUT:

Length: 6

Rearranged Sentence:

INVENTION IS MOTHER NECESSITY OF THE

Example 2:

INPUT: BE GOOD TO OTHERS.

OUTPUT:

Length: 4

Rearranged Sentence: BE GOOD OTHERS TO


Solution :
import java.io.*;
class WordsInSentence {
public void take() throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String str, words[], stk = "";
int i, j, c = 0, flag, len;
char ch;

// Loop to take input until the sentence is entered in all uppercase


while (true) {
flag = 0;
System.out.println("Enter the sentence:");
str = br.readLine();
len = str.length();
words = new String[len];

for (i = 0; i < len; i++) {


if (Character.isLowerCase(str.charAt(i))) {
flag = 1;
break;
}
}

if (flag == 0)
break;
else
System.out.println("Enter the sentence again with all
uppercase letters");
}

i = 0;

// Loop to split the sentence into words and store them in an array
while (i < len) {
ch = str.charAt(i);
if (ch == ' ' || ch == '.' || ch == '?' || ch == '!') {
words[c] = stk;
c++;
i++;
stk = "";
} else {
stk += ch;
i++;
}
}

// Bubble sort to rearrange words in alphabetical order


for (i = 0; i < c; i++) {
for (j = 0; j < c - 1; j++) {
if ((words[j].compareTo(words[j + 1])) > 0) {
stk = words[j];
words[j] = words[j + 1];
words[j + 1] = stk;
}
}
}

System.out.println("Length= " + c);


System.out.println("\nRearranged Sentence:\n");

// Displaying the rearranged words


for (i = 0; i < c; i++)
System.out.print(words[i] + " ");
}

public static void main() throws IOException {


WordsInSentence ob = new WordsInSentence();
ob.take(); }}
Question 7.

The names of the teams participating in a competition should be displayed on a banner vertically, to accommodate as
many teams as possible in a single banner. Design a program to accept the names of N teams, where 2 < N < 9 and
display them in vertical order, side by side with a horizontal tab (i.e. eight spaces).

Test your program for the following data and some random data:

Example 1

INPUT:
N=3
Team 1: Emus
Team 2: Road Rols
Team 3: Coyote

OUTPUT:
E R C
m o o
u a y
s d o
t
R e
o
l
s

Example 2

INPUT:
N=4
Team 1: Royal
Team 2: Mars
Team 3: De Rose
Team 4: Kings

OUTPUT:
R M D K
o a e i
y r n
a s R g
l o s
s
e

Example 3

INPUT:
N = 10

OUTPUT:
INVALID INPUT
Solution:

import java.util.Scanner;

public class Banner {


public static void main() {
Scanner in = new Scanner(System.in);
System.out.print("ENTER THE VALUE OF N: ");
int n = in.nextInt(); // Taking input for the number of teams
in.nextLine(); // Consuming the newline character

// Checking for valid input range


if (n <= 2 || n >= 9) {
System.out.println("INVALID INPUT");
return;
}

String teams[] = new String[n]; // Creating an array to store team names


int highLen = 0; // Variable to store the length of the longest team name

// Getting names for each team


for (int i = 0; i < n; i++) {
System.out.print("Team " + (i+1) + ": ");
teams[i] = in.nextLine(); // Storing team names in the array

// Finding the length of the longest team name


if (teams[i].length() > highLen) {
highLen = teams[i].length();
}
}

// Printing the banner


for (int i = 0; i < highLen; i++) {
for (int j = 0; j < n; j++) {
int len = teams[j].length();

// Checking if the current team name has characters at the current position
if (i >= len) {
System.out.print(" \t"); // Printing spaces if no character exists
}
else {
System.out.print(teams[j].charAt(i) + "\t"); // Printing the character
}
}
System.out.println(); // Moving to the next line for the next row of characters
} }}
Question 8.

Write a program to accept a sentence which may be terminated by either ‘.’, ‘?’ or ‘!’ only. The words are to be
separated by a single blank space and are in uppercase.

Perform the following tasks:

(a) Check for the validity of the accepted sentence.

(b) Convert the non-palindrome words of the sentence into palindrome words by concatenating the word by its
reverse (excluding the last character).

Example:

The reverse of the word HELP would be LEH (omitting the last alphabet) and by concatenating both, the new
palindrome word is HELPLEH. Thus, the word HELP becomes HELPLEH.

Note: The words which end with repeated alphabets, for example ABB would become ABBA and not ABBBA and
XAZZZ becomes XAZZZAX.

[Palindrome word: Spells same from either side. Example: DAD, MADAM etc.]

(c) Display the original sentence along with the converted sentence.

Test your program for the following data and some random data:

Example 1

INPUT:
THE BIRD IS FLYING.

OUTPUT:
THE BIRD IS FLYING.
THEHT BIRDRIB ISI FLYINGNIYLF

Example 2

INPUT:
IS THE WATER LEVEL RISING?

OUTPUT:
IS THE WATER LEVEL RISING?
ISI THEHT WATERETAW LEVEL RISINGNISIR

Example 3

INPUT:
THIS MOBILE APP LOOKS FINE.

OUTPUT:
THIS MOBILE APP LOOKS FINE.
THISIHT MOBILELIBOM APPA LOOKSKOOL FINENIF
Solution :
import java.util.*;

public class Palindrome {

// Method to check if a word is a palindrome


public static boolean isPalindrome(String word) {
boolean palin = true; // Assume the word is a palindrome

int len = word.length();


// Check characters from start and end to validate palindrome
for (int i = 0; i <= len / 2; i++) {
if (word.charAt(i) != word.charAt(len - 1 - i)) {
palin = false; // If characters don't match, it's not a palindrome
break;
}
}

return palin;
}

// Method to make a word into a palindrome


public static String makePalindrome(String word) {
int len = word.length();
char lastChar = word.charAt(len - 1);
int i = len - 1;
// Find the index where the characters differ from the last character
while (word.charAt(i) == lastChar) {
i--;
}

StringBuffer sb = new StringBuffer(word);


// Append characters in reverse order to make it a palindrome
for (int j = i; j >= 0; j--) {
sb.append(word.charAt(j));
}

return sb.toString();
}

public static void main() {


Scanner in = new Scanner(System.in);
System.out.println("ENTER THE SENTENCE:");
String ipStr = in.nextLine().trim().toUpperCase(); // Read input and convert to uppercase
int len = ipStr.length();
char lastChar = ipStr.charAt(len - 1);
// Check if the sentence ends with valid punctuation
if (lastChar != '.' && lastChar != '?' && lastChar != '!') {
System.out.println("INVALID INPUT");
return;
}
String str = ipStr.substring(0, len - 1); // Extract sentence without punctuation

StringTokenizer st = new StringTokenizer(str); // Tokenize the sentence


StringBuffer sb = new StringBuffer();

// Loop through each word in the sentence


while (st.hasMoreTokens()) {
String word = st.nextToken();
boolean isPalinWord = isPalindrome(word); // Check if the word is a palindrome

if (isPalinWord) {
sb.append(word); // If it's a palindrome, append as is
} else {
String palinWord = makePalindrome(word); // If not, make it a palindrome
sb.append(palinWord);
}
sb.append(" "); // Add space between words
}

String convertedStr = sb.toString().trim(); // Final converted sentence

// Output the original and converted sentences


System.out.println();
System.out.println(ipStr);
System.out.println(convertedStr);
}
}
Question 9

Caesar Cipher is an encryption technique which is implemented as ROT13 ('rotate by 13 places'). It is a


simple letter substitution cipher that replaces a letter with the letter 13 places after it in the alphabets, with
the other characters remaining unchanged.

ROT13

A/a B/b C/c D/d E/e F/f G/g H/h I/i J/j K/k L/l M/m

↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕

N/n O/o P/p Q/q R/r S/s T/t U/u V/v W/w X/x Y/y Z/z

Write a program to accept a plain text of length L, where L must be greater than 3 and less than 100.

Encrypt the text if valid as per the Caesar Cipher.

Test your program with the sample data and some random data.

Example 1

INPUT:
Hello! How are you?

OUTPUT:
The cipher text is:
Uryyb! Ubj ner lbh?

Example 2

INPUT:
Encryption helps to secure data.

OUTPUT:
The cipher text is:
Rapelcgvba urycf gb frpher qngn.

Example 3

INPUT:
You

OUTPUT:
INVALID LENGTH
Solution :

import java.util.Scanner;

public class CaesarCipher {

public static void main() {


Scanner in = new Scanner(System.in);
System.out.println("Enter plain text:");
String str = in.nextLine();
int len = str.length();

// Check for valid input length


if (len <= 3 || len >= 100) {
System.out.println("INVALID LENGTH");
return;
}

StringBuffer sb = new StringBuffer();


for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
// Shift characters in the range 'A'-'M' or 'a'-'m' by 13 positions forward
if ((ch >= 'A' && ch <= 'M') || (ch >= 'a' && ch <= 'm')) {
sb.append((char)(ch + 13));
}
// Shift characters in the range 'N'-'Z' or 'n'-'z' by 13 positions backward
else if ((ch >= 'N' && ch <= 'Z') || (ch >= 'n' && ch <= 'z')) {
sb.append((char)(ch - 13));
}
else {
sb.append(ch); // Keep non-alphabetic characters unchanged
}
}

String cipher = sb.toString(); // Convert StringBuffer to String


System.out.println("The cipher text is:");
System.out.println(cipher);
}
}
Question 10
Write a program to accept a sentence which may be terminated by either '.', '?' or '!' only. The
words may be separated by more than one blank space and are in UPPER CASE.
Perform the following tasks:

1. Find the number of words beginning and ending with a vowel.


2. Place the words which begin and end with a vowel at the beginning, followed by the
remaining words as they occur in the sentence.

Test your program with the sample data and some random data:
Example 1
INPUT:
ANAMIKA AND SUSAN ARE NEVER GOING TO QUARREL ANYMORE.
OUTPUT:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 3
ANAMIKA ARE ANYMORE AND SUSAN NEVER GOING TO QUARREL
Example 2
INPUT:
YOU MUST AIM TO BE A BETTER PERSON TOMORROW THAN YOU ARE TODAY.
OUTPUT:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 2
A ARE YOU MUST AIM TO BE BETTER PERSON TOMORROW THAN YOU TODAY
Example 3
INPUT:
LOOK BEFORE YOU LEAP.
OUTPUT:
NUMBER OF WORDS BEGINNING AND ENDING WITH A VOWEL = 0
LOOK BEFORE YOU LEAP
Example 4
INPUT:
HOW ARE YOU@
OUTPUT:
INVALID INPUT
Solution :

import java.util.*;
public class VowelWord {
public static void main() {
Scanner in = new Scanner(System.in);
System.out.println("ENTER THE SENTENCE:");
String ipStr = in.nextLine().trim().toUpperCase();
int len = ipStr.length();
char lastChar = ipStr.charAt(len - 1);
if (lastChar != '.' && lastChar != '?' && lastChar != '!') {
System.out.println("INVALID INPUT");
return;}
String str = ipStr.substring(0, len - 1);
StringTokenizer st = new StringTokenizer(str);
StringBuffer sbVowel = new StringBuffer();
StringBuffer sb = new StringBuffer();
int c = 0; // Counter for words beginning and ending with a vowel
while (st.hasMoreTokens()) {
String word = st.nextToken();
int wordLen = word.length();
// Checking if the word starts and ends with a vowel
if (isVowel(word.charAt(0)) && isVowel(word.charAt(wordLen - 1))) {
c++; // Increment count for words starting and ending with a vowel
sbVowel.append(word); // Append to buffer for words meeting criteria
sbVowel.append(" ");
} else {
sb.append(word); // Append other words to a separate buffer
sb.append(" ");} }
String newStr = sbVowel.toString() + sb.toString(); // Concatenating the buffers
System.out.println("NUMBER OF WORDS BEGINNING AND ENDING WITH A
VOWEL = " + c);
System.out.println(newStr); // Outputting the resulting string
}

// Function to check if a character is a vowel


public static boolean isVowel(char ch) {
ch = Character.toUpperCase(ch); // Convert character to uppercase
boolean ret = false;
// Checking if the character is one of the vowels
if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
ret = true; // If it's a vowel, set return value to true
}
return ret;
}
}

You might also like