KEMBAR78
Class X ICSE - String Handling Exercises | PDF | String (Computer Science) | Software Engineering
0% found this document useful (0 votes)
139 views24 pages

Class X ICSE - String Handling Exercises

The document contains a series of Java programming exercises focused on string handling. Each exercise includes a problem statement, sample input/output, and a Java code solution that demonstrates various string manipulation techniques such as removing vowels, finding the longest word, reversing words, and checking for palindromes. The exercises are designed for Class X ICSE students to enhance their understanding of string operations in Java.

Uploaded by

nanditha629
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)
139 views24 pages

Class X ICSE - String Handling Exercises

The document contains a series of Java programming exercises focused on string handling. Each exercise includes a problem statement, sample input/output, and a Java code solution that demonstrates various string manipulation techniques such as removing vowels, finding the longest word, reversing words, and checking for palindromes. The exercises are designed for Class X ICSE students to enhance their understanding of string operations in Java.

Uploaded by

nanditha629
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/ 24

Class X ICSE - String handling Exercises

1. Write a program in Java to accept a word/a string and display the new string
after removing all the vowels present in it.
Sample Input: COMPUTER APPLICATIONS
Sample Output: CMPTR PPLCTNS

import java.util.Scanner;

public class RemoveVowels {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a word or string: ");


String input = sc.nextLine();
String result = "";

// Loop through each character


for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);

// Check if the character is not a vowel


ch = Character.toUpperCase(ch); // convert to uppercase for uniformity
if (ch != 'A' && ch != 'E' && ch != 'I' && ch != 'O' && ch != 'U'){
result += ch;
}
}
System.out.println("String after removing vowels: " + result);
}
}
2. Write a program in Java to enter a string/sentence and display the
longest word and the length of the longest word present in the string.
Sample Input: “TATA FOOTBALL ACADEMY WILL PLAY AGAINST
MOHAN BAGAN” [2009]
Sample output: The longest word: FOOTBALL
The length of the word: 8

import java.util.Scanner;
public class LongestWordFinder {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = sc.nextLine();
String longestWord = "";
String currentWord = "";
int maxLength = 0;

// Add a space at the end to process the last word


sentence = sentence + " ";

for (int i = 0; i < sentence.length(); i++) {


char ch = sentence.charAt(i);

if (ch != ' ') {


currentWord += ch; // Build current word
} else {
if (currentWord.length() > maxLength) {
maxLength = currentWord.length();
longestWord = currentWord;
}
currentWord = "";
}
}
System.out.println("The longest word: " + longestWord);
System.out.println("The length of the word: " + maxLength);
}
}
3. Write a program in java to accept a string in uppercase and replace all the
vowels present in the string with asterisk(*) sign.
Sample input: TATA STEEL IS IN JAMSHEDPUR
Sample output: T*T* ST**L *S *N J*MSH*DP*R

import java.util.Scanner;
public class ReplaceVowels {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a string in uppercase: ");


String input = sc.nextLine();
String result = "";

// Loop through each character


for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);

// Check if character is a vowel


if (ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
result += '*';
} else {
result += ch;
}
}
System.out.println("String after replacing vowels: " + result);
}
}
4. Write a program in java to enter a sentence. Frame a word by joining all the
first characters of each word of the sentence. Display the word.
Sample input: Vital information resource under seize
Sample output: Virus

import java.util.Scanner;

public class FirstLetters {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = sc.nextLine();
sentence = " " + sentence;
String result = "";

for (int i = 1; i < sentence.length(); i++) {


char prev = sentence.charAt(i - 1);
char curr = sentence.charAt(i);

if (prev == ' ' && curr != ' ') {


result += curr;
}
}

System.out.println("The word formed is: " + result);


}
}
5.Write a program in java to enter a sentence. Display the words which are only
palindrome.
Sample input: Mom and Dad are not at home.
Sample output: Mom
Dad

import java.util.Scanner;

public class PalindromeWords {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
sentence = " " + sentence + " ";
String word = "";

System.out.println("Palindrome words:");
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);

if (Character.isLetter(ch)) {
word += ch; // build the word
} else if (word.length() > 0) {
// Check palindrome directly here
String lowerWord = word.toLowerCase();
int left = 0, right = lowerWord.length() - 1;
boolean isPalin = true;
while (left < right) {
if (lowerWord.charAt(left) != lowerWord.charAt(right)) {
isPalin = false;
break;
}
left++;
right--;
}
if (isPalin) {
System.out.println(word);
}
word = ""; // reset for next word
}
}
}
}
6. Write a program to accept a sentence. Display the sentence in reversing order
of its words.
Sample input: Computer is fun
Sample output: fun is Computer

import java.util.Scanner;

public class ReverseWords {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("Enter a sentence:");
String sentence = sc.nextLine();

sentence = sentence + " ";

String[] words = new String[50]; // assuming max 50 words


int count = 0;
String word = "";

// Extract words
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch != ' ') {
word += ch;
} else if (word.length() > 0) {
words[count] = word;
count++;
word = "";
}
}

// Display words in reverse order


for (int i = count - 1; i >= 0; i--) {
System.out.print(words[i]);
if (i > 0) {
System.out.print(" ");
}
}
}
}
7. Write a program to input a sentence and display the word of the sentence that
contain maximum vowels.
Sample input: Happy new year
Sample output: The word with maximum numbers of vowels is : year

import java.util.Scanner;
public class MaxVowelWord {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence:");
String sentence = sc.nextLine();
sentence = sentence + " ";
String word = "";
String maxVowelWord = "";
int maxVowelCount = 0;

for (int i = 0; i < sentence.length(); i++) {


char ch = sentence.charAt(i);

if (ch != ' ') {


word += ch; // build current word
} else if (word.length() > 0) {
int vowelCount = 0;

for (int j = 0; j < word.length(); j++) {


char c = Character.toLowerCase(word.charAt(j));
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
// Check if this word has more vowels than the current max
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
maxVowelWord = word;
}
word = ""; // reset for next word
}
}
if (!maxVowelWord.equals("")) {
System.out.println("The word with maximum numbers of vowels is : " +
maxVowelWord);
} else {
System.out.println("No word found!");
}
}
}

8. Write a program to accept to accept a word and convert it into lower


case, if it is in uppercase. Display the new word by replacing only the
vowels with the letter following it.
Sample Input: computer
Sample output: cpmpvtfr

import java.util.Scanner;
public class VowelReplacer {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a word: ");


String word = sc.nextLine();

word = word.toLowerCase();

String newWord = "";

for (int i = 0; i < word.length(); i++) {


char ch = word.charAt(i);

// Check if the character is a vowel


if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
// Replace with next character
ch = (char)(ch + 1);
}

newWord += ch;
}

System.out.println("Modified word: " + newWord);


}
}
9. Write a program to input a sentence and convert it into uppercase and
count and display the total number of words starting with letter ‘A’.
Sample input: advancement and application of information technology are
ever changing.
Sample output: ADVANCEMENT AND APPLICATION OF
INFORMATION TECHNOLOGY ARE EVER CHANGING.
Total number of words starting with letter ‘A’ = 4

import java.util.Scanner;
public class WordsWithA {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = sc.nextLine();

String upperSentence = sentence.toUpperCase();

int count = 0;
String word = "";

// Add a space at the end to process the last word


upperSentence = upperSentence + " ";

for (int i = 0; i < upperSentence.length(); i++) {


char ch = upperSentence.charAt(i);

if (ch != ' ') {


word += ch; // Build the current word
} else {
if (!word.equals("") && word.charAt(0) == 'A') {
count++;
}
word = ""; // Reset for next word
}
}
System.out.println(upperSentence);
System.out.println("Total number of words starting with letter ‘A’ = " + count);
}
}
10. Write a program to input a sentence and convert it into uppercase and
display each word in a separate line.
Sample input: India is my country.
Sample output: INDIA
IS
MY
COUNTRY

import java.util.Scanner;
public class WordPerLineUppercase {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = sc.nextLine();

sentence = sentence.toUpperCase();

String word = "";


sentence = sentence + " ";

for (int i = 0; i < sentence.length(); i++) {


char ch = sentence.charAt(i);

if (ch != ' ') {


word += ch; // Build the word
} else {
if (!word.equals("")) {
System.out.println(word);
word = ""; // Reset for next word
}
}
}
}
}
11. Write a program to accept 2 strings of same length. Form a new word in
such a way that the first character of the first word is followed by the first
character of the second word and so on.
Input string 1: BALL
Input string 2: WORD
Sample output: BWAOLRLD

import java.util.Scanner;
public class MergeStrings {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first string: ");
String str1 = sc.nextLine();
System.out.print("Enter second string: ");
String str2 = sc.nextLine();

if (str1.length() != str2.length()) {
System.out.println("Error: Strings must be of the same length.");
return;
}
// Create new word by combining alternate characters
String newWord = "";
for (int i = 0; i < str1.length(); i++) {
newWord += str1.charAt(i); // Character from first string
newWord += str2.charAt(i); // Character from second string
}
System.out.println("Merged word: " + newWord);
}
}
12. Write a program to accept a string. Convert the string into uppercase
letters. Count and output the number of double letter sequences that
existed in the string.
Sample input:” She was feeding the little rabbit with an apple”
Sample output: 4

import java.util.Scanner;

public class DoubleLetterCount {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter a sentence: ");


String sentence = sc.nextLine();

sentence = sentence.toUpperCase();

int count = 0;
for (int i = 0; i < sentence.length() - 1; i++) {
char current = sentence.charAt(i);
char next = sentence.charAt(i + 1);

if (current = = next && Character.isLetter(current)) {


count++;
// Skip the next character to avoid overlapping (e.g., 'AAA' should
// count only 1 'AA')
i++;
}
}

System.out.println("Number of double letter sequences: " + count);


}
}
13. Special words are those words which start and end with the same letter.
Example: EXISTENCE, COMIC, WINDOW
Palindrome words are those words which read the same from left to right
and vice-versa.
Example: MALAYALAM, MADAM, LEVEL, ROTATOR, CIVIC.
All palindromes are special words but all special words are not
palindromes. Write a program to accept a word. Check and display
whether the word is a palindrome or only a special word or none of them.

import java.util.Scanner;
public class WordChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter a word: ");


String word = scanner.nextLine().toUpperCase(); // Convert to uppercase
int length = word.length();
boolean isPalindrome = true;

// Check for palindrome


for (int i = 0; i < length / 2; i++) {
if (word.charAt(i) != word.charAt(length - 1 - i)) {
isPalindrome = false;
break;
}
}
// Check for special word (first and last character are same)
boolean isSpecial = word.charAt(0) == word.charAt(length - 1);

if (isPalindrome) {
System.out.println("The word is a Palindrome and also a Special
word.");
} else if (isSpecial) {
System.out.println("The word is a Special word.");
} else {
System.out.println("The word is neither a Palindrome nor a Special
word.");
}
}
}
14. Write a program to input a sentence. Convert the sentence into uppercase
letters. Display the words along with frequency of the words which have atleast
a pair of consecutive letters.
Sample input: Modem is an electronic device.
Sample output:
Modem
Device

import java.util.Scanner;

public class ConsecutiveLetters {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input sentence and convert to uppercase


System.out.println("Enter a sentence:");
String sentence = sc.nextLine().toUpperCase();

// Add space at the end for easy word extraction


sentence = sentence + " ";

String[] words = new String[50]; // assuming max 50 words


int count = 0;
String word = "";

// Extract all words


for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch != ' ') {
word += ch;
} else if (word.length() > 0) {
words[count] = word;
count++;
word = "";
}
}

// Check each stored word for consecutive alphabetical letters


System.out.println("Words with at least one pair of consecutive letters:");
for (int i = 0; i < count; i++) {
boolean hasPair = false;
for (int j = 0; j < words[i].length() - 1; j++) {
if (words[i].charAt(j) + 1 == words[i].charAt(j + 1)) {
hasPair = true;
break;
}
}
if (hasPair) {
System.out.println(words[i]);
}
}
}
}
15. Write a program to accept a word(say, BLUEJ) and display the pattern:
a) B L U E J b) J c) B L U E J
BLUE EE LUEJ
BLU UUU UEJ
BL LLLL EJ
B BBBBB J

import java.util.Scanner;
public class WordPatterns {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("Enter a word:");
String word = sc.nextLine().toUpperCase();
int len = word.length();

// Pattern (a)
System.out.println("Pattern (a):");
for (int i = len; i >= 1; i--) {
for (int j = 0; j < i; j++) {
System.out.print(word.charAt(j) + " ");
}
System.out.println();
}
// Pattern (b)
System.out.println("\nPattern (b):");
for (int i = 0; i < len; i++) {
for (int j = 0; j <= i; j++) {
System.out.print(word.charAt(len - 1 - i) + " ");
}
System.out.println();
}

// Pattern (c)
System.out.println("\nPattern (c):");
for (int i = 0; i < len; i++) {
for (int j = i; j < len; j++) {
System.out.print(word.charAt(j) + " ");
}
System.out.println();
}
}
}
16. Write a program to generate a triangle or an inverted triangle based
upon the user’s choice:
Example 1: Example 2:
Input: Type 1 for a triangle and Type Input: Type 1 for a triangle and Type
2 for an inverted triangle. 2 for an inverted triangle.
Enter your choice: 1 Enter your choice: 2
Enter a word: BLUEJ Enter a word: BLUEJ
Sample output: Sample output:
B BLUEJ
BL BLUE
BLU BLU
BLUE BL
BLUEJ B

import java.util.Scanner;
public class TrianglePattern {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Type 1 for a triangle and ");
System.out.println("Type 2 for an inverted triangle.");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();
System.out.print("Enter a word: ");
String word = sc.nextLine().toUpperCase();
int len = word.length();
if (choice = = 1) {
// Triangle
for (int i = 1; i <= len; i++) {
for (int j = 0; j < i; j++) {
System.out.print(word.charAt(j) + " ");
}
System.out.println();
}
}
else if (choice == 2) {
// Inverted triangle
for (int i = len; i >= 1; i--) {
for (int j = 0; j < i; j++) {
System.out.print(word.charAt(j) + " ");
}
System.out.println();
}
} else {
System.out.println("Invalid choice.");
}
}
}

17. Using the switch statement, write a menu driven program for the
following:

a) To print Floyd’s triangle b) To display the following pattern


1 I
2 3 IC
4 5 6 ICS
7 8 9 10 ICSE
11 12 13 14 15
For an incorrect option, an appropriate error message should be displayed.
[2016]

import java.util.Scanner;

public class MenuPatterns {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.println("Menu:");
System.out.println("1. Print Floyd’s Triangle");
System.out.println("2. Display ICSE Pattern");
System.out.print("Enter your choice (1 or 2): ");
int choice = sc.nextInt();

switch (choice) {
case 1:
// Floyd's Triangle
System.out.print("Enter number of rows: ");
int rows = sc.nextInt();
int num = 1;
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
System.out.print(num + "\t");
num++;
}
System.out.println();
}
break;
case 2:
// ICSE pattern
String word = "ICSE";
for (int i = 0; i < word.length(); i++) {
for (int j = 0; j <= i; j++) {
System.out.print(word.charAt(j) + " ");
}
System.out.println();
}
break;

default:
System.out.println("Invalid choice! Please enter 1 or 2.");
}
}
}

18. Define a class to accept 10 characters in an array. The program searches for
the existence of a given character in the array using linear search. If found then
print the character along with the index (location in the array), otherwise display
an appropriate message “No such character is available in the array”.

import java.util.Scanner;

public class CharSearch {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

char[] arr = new char[10];

System.out.println("Enter 10 characters:");
for (int i = 0; i < 10; i++) {
arr[i] = sc.next().charAt(0);
}

System.out.print("Enter character to search: ");


char search = sc.next().charAt(0);

boolean found = false;


for (int i = 0; i < 10; i++) {
if (arr[i] == search) {
System.out.println("Character '" + search + "' found at index: " + i);
found = true;
break; // stop after first match
}
}

if (!found) {
System.out.println("No such character is available in the array");
}
}
}

19. Write a program in java to store ten different countries’ name and their
capitals in two different Single Dimensional Arrays (SDAs). Display the
countries names (that start with a vowel) along with their capital in the given
format.
Countries Name Capital
xxxx xxx
xxxx xxx

import java.util.Scanner;

public class CountriesAndCapitals {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String[] countries = new String[10];


String[] capitals = new String[10];

// Input 10 countries and their capitals


System.out.println("Enter 10 countries and their capitals:");
for (int i = 0; i < 10; i++) {
System.out.print("Country " + (i + 1) + ": ");
countries[i] = sc.nextLine();
System.out.print("Capital of " + countries[i] + ": ");
capitals[i] = sc.nextLine();
}

// Display header
System.out.printf("Countries Name \tCapital");

// Display countries starting with a vowel


for (int i = 0; i < 10; i++) {
char firstChar = Character.toUpperCase(countries[i].charAt(0));
if (firstChar == 'A' || firstChar == 'E' || firstChar == 'I' || firstChar == 'O' ||
firstChar == 'U') {
System.out.printf( countries[i]+”\t”+capitals[i]);
}
}
}
}

20. Write a program in java to store 20 different names and telephone numbers
of your friends in two different Single Dimensional Arrays (SDAs). Now
arrange all the names in alphabetical order and display all the names along with
their respective telephone numbers. Use selection sort technique.

import java.util.Scanner;

public class FriendsDirectory {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String[] names = new String[20];


String[] phoneNumbers = new String[20];

// Input names and phone numbers


System.out.println("Enter 20 names and their telephone numbers:");
for (int i = 0; i < 20; i++) {
System.out.print("Name " + (i + 1) + ": ");
names[i] = sc.nextLine();
System.out.print("Phone Number for " + names[i] + ": ");
phoneNumbers[i] = sc.nextLine();
}

// Selection Sort by names


for (int i = 0; i < 19; i++) {
int minIndex = i;
for (int j = i + 1; j < 20; j++) {
if (names[j].compareToIgnoreCase(names[minIndex]) < 0) {
minIndex = j;
}
}
// Swap names
String tempName = names[i];
names[i] = names[minIndex];
names[minIndex] = tempName;

// Swap corresponding phone numbers


String tempPhone = phoneNumbers[i];
phoneNumbers[i] = phoneNumbers[minIndex];
phoneNumbers[minIndex] = tempPhone;
}

// Display sorted names with numbers


System.out.printf("Name \t Phone Number");
for (int i = 0; i < 20; i++) {
System.out.printf(names[i]+”\t”+ phoneNumbers[i]);
}
}
}

21. Write a program to accept 10 names in a Single Dimensional Array (SDA).


Display the names whose first letter matches with the letter entered by the user.
Sample input: Aman Sahi
Akash Gupta
Suman Mishra and so on.
Sample output: Enter a letter: A
Aman Sahi
Akash Gupta

import java.util.Scanner;

public class NameFilter {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String[] names = new String[10];


System.out.println("Enter 10 names:");
for (int i = 0; i < 10; i++) {
names[i] = sc.nextLine();
}

System.out.print("Enter a letter: ");


char letter = sc.next().charAt(0);
letter = Character.toUpperCase(letter);

// Display matching names


System.out.println("Names starting with '" + letter + "':");
for (int i = 0; i < 10; i++) {
if (Character.toUpperCase(names[i].charAt(0)) == letter) {
System.out.println(names[i]);
}
}
}
}

22. Write a program to accept the names of 10 cities in a single dimensional


string array and their STD codes in another single dimensional integer
array. Search for the name of a city input by the user in the list. If found,
display “Search successful” and print the name of the city along with its
STD code, or else display the message “No such city in the list !!”. [2012]

import java.util.Scanner;
public class CitySearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

String[] cities = new String[10];


int[] stdCodes = new int[10];

System.out.println("Enter the names of 10 cities and their STD codes:");


for (int i = 0; i < 10; i++) {
System.out.print("City " + (i + 1) + ": ");
cities[i] = sc.nextLine();
System.out.print("STD code for " + cities[i] + ": ");
stdCodes[i] = sc.nextInt();
sc.nextLine(); // consume newline
}
System.out.print("\nEnter the city name to search: ");
String searchCity = sc.nextLine();

boolean found = false;


for (int i = 0; i < 10; i++) {
if (cities[i].equalsIgnoreCase(searchCity)) {
System.out.println("Search successful");
System.out.println("City: " + cities[i]);
System.out.println("STD Code: " + stdCodes[i]);
found = true;
break;
}
}
if (!found) {
System.out.println("No such city in the list !!");
}
}
}

You might also like