APC Class 12 String Manipulations Solved
APC Class 12 String Manipulations Solved
String Manipulations
Class 12 - APC Understanding ISC Computer
Science with BlueJ
Solutions to Unsolved Programs
Question 1
Sample Output:
Solution
import java.util.Scanner;
/*
* Intialize low variables to
* highest ASCII code and
* high variables to lowest
* ASCII code
*/
char lowerCaseLow = 255;
char lowerCaseHigh = 0;
Shreyan Nag Computer Classes
char upperCaseLow = 255;
char upperCaseHigh = 0;
Output
Shreyan Nag Computer Classes
Question 2
Write a program in Java to enter a string in a mixed case. Arrange all the letters of string such
that all the lower case characters are followed by the upper case characters.
Sample Input:
Computer Science
Sample Output:
omputercienceCS
Solution
import java.util.Scanner;
System.out.println("Input String:");
System.out.println(str);
String newStr = sbLowerCase.append(sbUpperCase).toString();
System.out.println("Changed String:");
System.out.print(newStr);
}
}
Output
Question 3
Write a program in Java to accept a string. Arrange all the letters of the string in an
alphabetical order. Now, insert the missing letters in the sorted string to complete all the
letters between first and last characters of the string.
Sample Input:
computer
Alphabetical order:
cemoprtu
Sample Output:
cdefghijklmnopqrstu
Solution
import java.util.Scanner;
Shreyan Nag Computer Classes
public class StringSort
{
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string:");
String str = in.nextLine();
str = str.toLowerCase();
int len = str.length();
System.out.println("Alphabetical order:");
System.out.println(sortedStr);
System.out.println("Filled String:");
System.out.println(filledStr);
}
}
Output
Shreyan Nag Computer Classes
Question 4
Write a program in Java to accept a string. Count and display the frequency of each character
present in the string. The character with multiple frequencies should be displayed only once.
Sample Input:
golden jubilee
Sample Output:
Alphabet g o l d e n j u b i
Frequency 1 1 2 1 3 1 1 1 1 1
Solution
import java.util.Scanner;
if (Character.isWhitespace(ch)) {
continue;
}
if (seen) {
continue;
}
int f = 1;
for (int k = i + 1; k < len; k++) {
if (ch == str.charAt(k)) {
f++;
}
}
seenArr[idx] = ch;
freqArr[idx] = f;
idx++;
}
System.out.println();
for (int i = 0; i < idx; i++) {
System.out.print(freqArr[i] + " ");
}
}
}
Output
Shreyan Nag Computer Classes
Question 5
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
Solution
import java.util.*;
Output
Question 6
Write a program in Java to accept two strings. Display the new string by taking each
character of the first string from left to right and of the second string from right to left. The
letters should be taken alternatively from each string. Assume that the length of both the
strings are same.
Sample Input:
String 1: HISTORY
String 2: SCIENCE
Sample Output:
HEICSNTEOIRCYS
Solution
import java.util.Scanner;
System.out.println(newStr);
}
}
Output
Question 7
Write a program in Java to accept a four-letter word. Display all the probable four letter
combinations such that no letter should be repeated in the output within each combination.
Sample Input:
PARK
Sample Output:
PAKR, PKAR, PRAK, APRK, ARPK, AKPR, and so on.
Shreyan Nag Computer Classes
Solution
import java.util.Scanner;
if (len != 4) {
System.out.println("Invalid Input!");
System.out.println("Please enter a four letter word");
return;
}
Output
Shreyan Nag Computer Classes
Shreyan Nag Computer Classes
Question 8
While typing, a typist has created two or more consecutive blank spaces between the words
of a sentence. Write a program in Java to eliminate multiple blanks between the words by a
single blank.
Sample Input:
Indian Cricket team tour to Australia
Sample Output:
Indian Cricket team tour to Australia
Solution
import java.util.*;
while (st.hasMoreTokens()) {
String word = st.nextToken();
newStr += word + " ";
}
newStr = newStr.trim();
System.out.println("Output String:");
System.out.println(newStr);
}
}
Output
Shreyan Nag Computer Classes
Question 9
A new advanced Operating System, incorporating the latest hi-tech features has been
designed by Opera Computer Systems. The task of generating copy protection code to
prevent software privacy has been entrusted to the Security Department. The Security
Department has decided to have codes containing a jumbled combination of alternate
uppercase letters of the alphabet starting from A up to K (namely among A, C, E, G, I, K).
The code may or may not be in the consecutive series of alphabets. Each code should not
exceed 6 characters and there should be no repetition of characters. If it exceeds 6 characters,
display an appropriate error message.
Write a program to input a code and its length. At the first instance of an error display
"Invalid" stating the appropriate reason. In case of no error, display the message "Valid".
Sample Data:
Input:
n=4
ABCE
Output:
Invalid! Only alternate letters permitted!
Input:
n=4
AcIK
Output:
Invalid! Only uppercase letters permitted!
Input:
n=7
Shreyan Nag Computer Classes
Output:
Error! Length of String should not exceed 6 characters!
Input:
n=3
ACE
Output:
Valid
Input:
n=5
GEAIK
Output:
Valid
Solution
import java.util.Scanner;
System.out.println("Enter Code:");
String code = in.nextLine();
if (Character.isLowerCase(ch)) {
System.out.println("Invalid! Only uppercase letters
permitted!");
return;
}
/*
* ASCII Code should be odd as we
* are taking alternate letters
* between A and K. We have already
* checked above that letter is
* between A and K. Now if we check
* for odd then it means that letter
* is one of A, C, E, G, I, K
*/
if (ch % 2 == 0) {
System.out.println("Invalid! Only alternate letters
permitted!");
return;
}
/*
* Check for repetition
*/
int count = 0;
for (int j = 0; j < len; j++) {
if (ch == code.charAt(j)) {
count++;
}
}
if (count > 1) {
System.out.println("Invalid! Letter repetition is
not permitted!");
return;
}
}
System.out.println("Valid");
}
}
Output
Shreyan Nag Computer Classes
Shreyan Nag Computer Classes
Shreyan Nag Computer Classes
Question 10
The input in this question will consist of a number of lines of English text consisting of the
letters of the English alphabet, the punctuation marks (') apostrophe, (.) full stop (, ) comma,
(; ) semicolon, (:) colon and white space characters (blank, new line). Your task is to print the
words of the text in reverse order without any punctuation marks other than blanks.
Input Format:
This first line of input contains a single integer n ( < = 20), indicating the number of lines in
the input.
This is followed by lines of input text. Each line should accept a maximum of 80 characters.
Output Format:
Output the text containing the input lines in reverse order without punctuations except blanks
as illustrated above.
Test your program for the following data and some random data.
Sample Data:
Input:
2
Emotions controlled and directed to work, is character.
By Swami Vivekananda.
Output:
Vivekananda Swami By character is work to directed and controlled Emotions
Input:
1
Do not judge a book by its cover.
Output:
cover its by book a judge not Do
Solution
import java.util.*;
System.out.println("Enter Lines:");
String lines[] = new String[n];
for (int i = 0; i < n; i++) {
lines[i] = in.nextLine();
if (lines[i].length() > 80) {
System.out.println("Invalid line!");
System.out.println("Length should be within 80
characters");
return;
}
}
while (st.hasMoreTokens()) {
StringBuffer sbWord = new StringBuffer();
String word = st.nextToken();
int len = word.length();
for (int j = 0; j < len; j++) {
char ch = word.charAt(j);
if (!Character.isWhitespace(ch)
&& punctuations.indexOf(ch) == -1) {
sbWord.append(ch);
}
}
sbLine.insert(0, sbWord.toString());
sbLine.insert(0, " ");
}
}
}
}
Output
Shreyan Nag Computer Classes
Question 11
Read a single sentence which terminates with a full stop (.). The words are to be separated
with a single blank space and are in lower case. Arrange the words contained in the sentence
according to the length of the words in ascending order. If two words are of the same length
then the word occurring first in the input sentence should come first. For both, input and
output the sentence must begin in upper case.
Test your program for given data and also some random data:
Input:
The lines are printed in reverse order.
Output:
In the are lines order printed reverse.
Input:
Print the sentence in ascending order.
Output:
In the print order sentence ascending.
Shreyan Nag Computer Classes
Input:
I love my Country.
Output:
I my love Country.
Solution
import java.util.*;
if (str.charAt(len - 1) != '.') {
System.out.println("Invalid Input!");
System.out.println("Sentence should end with full
stop.");
return;
}
if (Character.isLowerCase(str.charAt(0))) {
System.out.println("Invalid Input!");
System.out.println("Sentence should start with upper
case letter.");
return;
}
strArr[0] = Character.toUpperCase(strArr[0].charAt(0))
+ strArr[0].substring(1);
System.out.println("Sorted String:");
for (int i = 0; i < wordCount; i++) {
System.out.print(strArr[i]);
if (i == wordCount - 1) {
System.out.print(".");
}
else {
System.out.print(" ");
}
}
}
}
Output
Shreyan Nag Computer Classes
Question 12
Write a program to read a string / sentence and output the number of times each word occurs
in the entire text. At the end, the output should be sorted into ascending order words along
with usage of words. You may assume that the entire text is in capitals (you may also convert
in capitals for your betterment) and each word is followed by a blank space except the last
one, which is followed by a full stop. Let there be at the most 50 words in the text.
Test your program for the given sample data and also some other random data:
SAMPLE DATA:
Shreyan Nag Computer Classes
Input:
YOU ARE GOOD WHEN YOUR THOUGHTS ARE GOOD AND YOUR DEEDS ARE
GOOD.
Output:
And 1
Are 3
Deeds 1
Good 3
Thoughts 1
When 1
You 1
Your 2
Input:
IF YOU FAIL TO PLAN YOU ARE PLANNING TO FAIL.
Output:
Are 1
Fail 2
If 1
Plan 1
Planning 1
Shreyan Nag Computer Classes
Words Word Count
To 2
You 2
Solution
import java.util.*;
Output
Shreyan Nag Computer Classes
Question 13
A string is said to be valid if it contains pair of parenthesis having text / alphabet such as
(TY) and the string is said to be invalid if it contains nested parenthesis such as (Y (UP)).
For example:
SUN (A(X) RISE) BEGINS FROM (RT) EAST is an "Invalid" string because in this string
nested parenthesis are present, but SUN (A) RISE BEGINS FROM (RT) EAST is a "Valid"
string because there is no nested parenthesis.
Sample Data:
Input:
SUN (a) RISE BEGINS FROM (RT) EAST
Output:
SUN RISE BEGINS FROM EAST
Input:
SUN (A (X) RISE) BEGINS FROM (RT) EAST
Output:
Sorry, an invalid string
Input:
COM(IPX)PUTER IS (MY) JUNK (GOOD) SYSTEM
Output:
COMPUTER IS JUNK SYSTEM
Solution
import java.util.*;
open = i;
}
if (open == -1) {
sb.append(ch);
}
Shreyan Nag Computer Classes
if (ch == ')') {
if (open == -1) {
System.out.println("Sorry, an invalid string");
return;
}
open = -1;
}
/*
* Using StringTokenizer to remove
* extra spaces between words
*/
}
}
Output
Shreyan Nag Computer Classes
Question 14
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:
1. Accept the number of sentences. If the number of sentences exceeds the limit, an
appropriate error message must be displayed.
2. Find the number of words in the whole paragraph.
Shreyan Nag Computer Classes
3. 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
Shreyan Nag Computer Classes
Word Frequency
YES 1
IT 1
THIS 2
IS 3
Example 3
Input:
Enter number of sentences. 5
Output:
Invalid Entry
Solution
import java.util.*;
if (n < 1 || n > 3) {
System.out.println("Invalid Entry");
return;
}
System.out.println("Enter sentences.");
String ipStr = in.nextLine();
ipStr = ipStr.toUpperCase();
System.out.println();
System.out.println("Total number of words: " + wordCount);
if (j == idx) {
wordArr[idx] = word;
wordFreq[idx]++;
idx++;
}
}
Output
Shreyan Nag Computer Classes
Shreyan Nag Computer Classes
Shreyan Nag Computer Classes
Question 15
ROT13
A/ B/ C/ D/ E/ F/ G/ H/ K/ M/
I/i J/j L/l
a b c d e f g h k m
↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕ ↕
N/ O/ P/ Q/ R/ S/ U/ V/ W/ X/ Y/
T/t Z/z
n o p q r s u v w x y
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?
Shreyan Nag Computer Classes
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;
Output
Shreyan Nag Computer Classes