STRINGS
STRINGS
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;
}
}
}
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.
(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
OUTPUT: IS IT RAINING?
YOU MAY GET WET IF IT IS RAINING.
COMMON WORDS FREQUENCY
IS 2
IT 2
RAINING 2
Example 2
NO COMMON WORDS
Example 4
// 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);
}
st = new StringTokenizer(sent[1]);
String words2[] = new String[st.countTokens()];
i = 0;
while (st.hasMoreTokens()) {
words2[i++] = st.nextToken();
}
A Palindrome is a word that may be read the same way in either direction.
Test your program with the sample data and some random data:
Example 1
Example 2
Example 3
import java.io.*;
import java.util.*;
class PalindromeChecker {
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
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.
Example 1
OUTPUT:
Intelligence Plus Character Is Education
Example 2
OUTPUT:
God is Great
Example 3
OUTPUT:
Invalid Input.
Solution:
import java.util.Scanner;
System.out.println("\nOUTPUT:");
System.out.println("\n\nWord\tVowels\tConsonants");
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.
(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
WORD TO BE DELETED: IS
WORD POSITION IN THE SENTENCE: 6
Example 2
WORD TO BE DELETED: SO
WORD POSITION IN THE SENTENCE: 4
Example 3
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();
int l = s.length();
char last = s.charAt(l-1);
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;
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:
Test your program with the sample data and some random data:
Example 1:
OUTPUT:
Length: 6
Rearranged Sentence:
Example 2:
OUTPUT:
Length: 4
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++;
}
}
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;
// 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.
(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.*;
return palin;
}
return sb.toString();
}
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
}
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.
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;
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
}