0% found this document useful (0 votes)
2 views16 pages

java String_program_day1[2]

The document outlines several programming tasks related to a messaging application, including features for reversing messages, counting vowels and consonants, checking for banned words, validating OTPs, and detecting palindromes. Each task includes input and output formats, constraints, and example code implementations in Java. The overall goal is to enhance user experience and content moderation within the application.

Uploaded by

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

java String_program_day1[2]

The document outlines several programming tasks related to a messaging application, including features for reversing messages, counting vowels and consonants, checking for banned words, validating OTPs, and detecting palindromes. Each task includes input and output formats, constraints, and example code implementations in Java. The overall goal is to enhance user experience and content moderation within the application.

Uploaded by

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

1.

You are developing a feature for a messaging application that allows users to
reverse any message they type. This feature will be used for fun, or to create
secret/encoded messages.

Write a function that takes a string input and returns the reversed version of that
string.

Input Format:-
=>A single line containing a string message (1 ≤ length ≤ 1000).

The string can contain:


::Alphabets (both uppercase and lowercase)
::Digits (0–9)
::Punctuation symbols (e.g., !@#$%^&*())

Output Format:-
-->Output a single line containing the reversed string.
Constraints
-->1 ≤ len(message) ≤ 1000

Example1:
Input : Hello, World!
output: !dlroW ,olleH
Code:

public static String reverse(String str) {


if (str == null || str.length( ) == 0)
return str;
String temp = "";
for (int i = str.length( ) - 1; i >= 0; i--) {
temp += str.charAt(i);
}
return temp;
}

-----------------------------------------------------------------------------------
--------------------------------
2.You are developing a statistics feature in a messaging app that analyzes user
messages. Your task is to write a function that counts the number of vowels and
consonants in a given message.

Ignore digits, special characters, and spaces while counting. Only English alphabet
letters (A–Z or a–z) are considered.

Input Format
A single string message representing the user's input.

The string may contain:


::Uppercase and lowercase letters
::Digits (0–9)
::Punctuation and special symbols
::Whitespaces

Output Format
Two integers:
-->The first integer is the number of vowels.
-->The second integer is the number of consonants.

Constraints
::1 ≤ len(message) ≤ 1000
::The comparison should be case-insensitive.
::Only alphabetic characters are counted (ignore numbers, punctuation, and
whitespace).

Example1:
Input : "Hello World!"
output: 3 7
Example2:
Input: "AI is the future!"
Output: 7 6

Code:
public static void countVowelsAndConsonants(String str) {
if (str == null) {
System.out.println("vowels : 0\nconsonants : 0");
return;
}
str = str.toLowerCase();
int vowelCount = 0, consonantCount = 0;

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


char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch ==
'u')
vowelCount++;
else if (ch >= 'a' && ch <= 'z')
consonantCount++;
}
System.out.println("vowels : " + vowelCount);
System.out.println("consonants : " + consonantCount);
}

-----------------------------------------------------------------------------------
---------------------------------
3.You are building a content moderation feature for a messaging app. Messages
containing banned words such as "bad", "hate", and "ugly" should be blocked to
ensure a positive user experience.

Write a function that checks whether a given input message contains any banned
word, and returns True if it does, otherwise False.

Input Format
::A string message containing the text input by the user.
::A predefined array of banned words:

Output Format
::Return True if any banned word is found in the message (case-insensitive).
::Return False if no banned words are present.

Constraints
::1 ≤ len(message) ≤ 1000
::The check should be case-insensitive.
::A banned word match should be found even if it's part of another word, e.g.,
"hateful" should be flagged for "hate".
::Punctuation is considered part of words (you don’t need to strip punctuation).

banned_words = ["bad", "hate", "ugly"]


Example1:
Input : "I think that is a bad idea"
output: true
Example2:
Input: "You are awesome!"
Output: false

Code:
public static boolean checkBannedWords(String msg) {
if (msg == null)
return false;
String[] bannedWord = { "bad", "sad", "cry" };
msg = msg.toLowerCase();
for (String word : bannedWord) {
if (msg.contains(word))
return true;
}
return false;
}

-----------------------------------------------------------------------------------
---------------------------------
4.You are building a feature for a messaging app that lets users check if their
message is a palindrome — a string that reads the same forwards and backwards when
ignoring case, spaces, and special characters.

Your task is to write a function that returns True if the cleaned version of the
input string is a palindrome, and False otherwise.
Input Format
A single string message of length 1 ≤ len(message) ≤ 1000

The string may contain:


::Letters (A–Z, a–z)
::Digits (0–9)
::Whitespace characters
::Punctuation/special characters (e.g., !@#$%^&*()_+[]{};:,.<>?)

Output Format
-->Return True if the cleaned message is a palindrome.
-->Return False otherwise.

Constraints
::All checks must be case-insensitive(convert it into lowercase).
::Ignore all non-alphanumeric characters.
::Must work with edge cases such as:
::Only punctuation/emojis
::Mixed casing
::Messages with leading/trailing whitespace

Example1:
Input : "Madam, in Eden, I’m Adam"
output: true
Example2:
Input: "Was it a car or a cat I saw?"
Output: true
Code:
package Scenarios;
public class PalindromeChars
{
public static boolean Palindrome(String s)
{
s=s.toLowerCase();
int left=0;
int right=s.length()-1;
while(left<right)
{
char ch1=s.charAt(left);
char ch2=s.charAt(right);
if(ch1>'z' || ch1<'a')//check if ch1 is spl char
left++;
else if(ch2>'z' || ch2<'a')//check if ch2 is spl char
right--;
else if(ch1!=ch2)//compare start and end char
return false;
else
{
left++;
right--;
}
}
return true;
}
public static void main(String[] args)
{
String s="Was it a car or a cat I saw";
System.out.println(Palindrome(s));
}
}

-----------------------------------------------------------------------------------
---------------------------------
5. Use Case: Validating OTPs (One-Time Passwords), PIN codes, or numeric
verification codes.
Example: A login form sends an OTP "123456" to a user’s phone and checks whether
the user input contains only digits.
Validation: Rejects if user enters "12a45" or "12 345".
Your task is to write a function that checks whether a given string consists only
of numeric digits.
The function should return True if every character in the string is a digit (0-9),
and False otherwise.

Input Format
::A single string message of length 1 ≤ len(message) ≤ 1000.
::The string may contain:
::Digits (0-9)
::Alphabetic characters (A–Z, a–z)
::Special characters or punctuation
::Whitespace

Output Format
::Return true if all characters in the string are digits.
::Return false if there is any non-digit character.

Constraints
::The string should be strictly composed of digits only.
::Whitespace, punctuation, and symbols must result in False.
::An empty string is invalid (i.e., not considered numeric).

Example1:
Input : "1234567890"
output: true

Example2:
Input: "1234abc"
Output: false

Code:
public static boolean otpValidation(String str) {
if (str == null || str.length() == 0)
return false;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch < '0' || ch > '9')
return false;
}
return true;
}

===================================================================
6.You are developing a symbol balancing tool for a text editor that processes
formatting or markdown-like symbols.

Given an input string S consisting solely of the characters '*' (asterisk) and '#'
(hash), determine whether the string is balanced or identify how many symbols need
to be added to achieve balance.

Definition of a Valid String:

A string is considered valid when it contains an equal number of '*' and '#'
characters.

Task:

If the number of '*' and '#' characters is equal,


print:balanced

If there are more '*' characters than '#', print:


<difference> # should be added

If there are more '#' characters than '*', print:


<difference> * should be added

Input Format:
A single line containing the string S, composed only of '*' and '#' characters.

Output Format:
A single line indicating the balance status as specified above.
Constraints:

use only one counter variable

1 ≤ length of S ≤ 1000

The string contains no spaces or other symbols.

TESTCASE 1:
Input:
"****#"
Output:
3 # should be added

TESTCASE 2:
Input:
*###
Output:
2 * should be added

TESTCASE 3:
Input:
**##
Output:
balanced

PROGRAM:
public class starsAndHashs
{
static int starAndHashCount(String s1){
int count=0;
for(int i=0;i<s1.length();i++){
if(s1.charAt(i)=='*')
{
count++;
}
else if(s1.charAt(i)=='#')
{
count--;
}
}
return count;
}

public static void main(String[] args)


{
int c=starAndHashCount("****#");
if(c<0) System.out.println(Math.abs(c)+" * should be added");
else if(c>0) System.out.println(c+" # should be added");
else System.out.println("balanced");
}
}
========================================
7]
You are given an array of strings. Your task is to write a Java program to find all
the palindromic strings in the array and return them in a new string array.
A palindrome is a word or phrase that reads the same forward and backward (e.g.,
"madam", "racecar").
You must use only standard Java libraries to solve this problem.

Input Format:
An array of strings
::1 ≤ length of each string ≤ 100
::1 ≤ number of strings in the array ≤ 1000

Output Format:
-->A new array containing only the strings from the original array that are
palindromes, in the same order.

Constraints:
::Case-sensitive comparison (i.e., "Madam" is not a palindrome).
::Do not use any third-party libraries.
::You may assume the input contains only valid strings.

Example 1:
Input:
["madam", "hello", "racecar", "apple", "noon"]
Output:
["madam", "racecar", "noon"]

Example 2:
Input:
["Java", "Python", "Level", "Rotor", "World"]
Output:
[]

program:
=====
public static String[] findAllPalindrome(String[] arr)
{
int count=0;
for(String str : arr)
{
if(isPalindrome(str))
count++;
}
String[] result = new String[count];
int index=0;
for(String str : arr)
{
if(isPalindrome(str))
result[index++]=str;
}
return result;
}
public static boolean isPalindrome(String str)
{
int i=0,j=str.length()-1;
while(i<j)
{
if(str.charAt(i)!=str.charAt(j))
return false;
i++;
j--;
}
return true;
}
public static void main(String[] args) {
String[] arr = {"Madam", "hello", "racecar", "apple", "noon"};
System.out.println(Arrays.toString(findAllPalindrome(arr)));
}

==========================================
8]

8.You are given a string s consisting of words and spaces.


Your task is to reverse the order of the words in the string and return the result
as a single string with:
-->Words separated by a single space
-->No leading or trailing spaces
-->No extra spaces between words
A word is defined as a sequence of non-space characters.

Input Format:
::A single line containing a string s
::1 ≤ s.length ≤ 10⁴
::The string may contain leading, trailing, or multiple spaces between words.

Output Format:
-->A single string with the words in reverse order, separated by a single space,
and with no extra spaces.

Constraints:
::The string contains only printable ASCII characters.
::All words are separated by at least one space.

Example 1:
Input:
"the sky is blue"
Output:
"blue is sky the"

Example 2:
Input:
" hello world "
Output:
"world hello"

code:
public class ReverseTheWords {

public static String reverseWords(String str)


{
//str=str.trim();
String result="";
//System.out.println(Arrays.toString(str.split("[ ]+")));
for(String s1: str.split("[ ]+"))
{
result=" "+s1+result;
}
return result.trim();
}
public static void main(String[] args) {
System.out.println(reverseWords(" Hello World "));
System.out.println(reverseWords("the sky is blue"));
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------
9.You are working on a text analytics feature for a content moderation system in a
chat or social media application.
One of the requirements is to detect the longest word in a user-submitted message.
This helps in identifying unusually long words that might be spam or gibberish.

Your task is to implement a program that takes a user's input string (message) and
returns the longest word from it.

Input Format:
::A single line of input containing a sentence s
::1 ≤ s.length ≤ 1000

The sentence may include:


::Uppercase/lowercase letters
::Extra spaces (Leading Space, Trailing space)
::No punctuation (for simplicity in this version)

Output Format:
::Print the longest word in the input
::If two or more words have the same length, return the first one

Example 1:
Input:
"I absolutely love programming and solving problems"
Output:
"programming"

Example 2:
Input:
" Artificial Intelligence is amazing "
Output:
"Intelligence"

code:
public class FindTheLongestWord {

public static String findTheLongestWord(String str)


{
str=str.trim();
int max=Integer.MIN_VALUE;
String result=null;
String[] srr=str.split(" ");
for(String s1 : srr)
{
int length=s1.length();
if(max<length)
{
max=length;
result=s1;
}
}
return result;
}

public static void main(String[] args) {


System.out.println(findTheLongestWord("I absolutely love programming
and solving problems"));
System.out.println(findTheLongestWord(" Artificial Intelligence is
amazing "));
}
}

-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
10. You are developing a search and filtering feature for a contacts or messaging
application.
The feature should allow users to filter names or words based on the starting
letter they input.

Your task is to write a program that takes:


->An array of strings (e.g., names, tags, etc.)
->A single character representing the starting letter
And returns all the strings from the array that begin with the given letter (case-
insensitive).

Input Format:
::First line: An integer n — number of strings in the array
::Next n lines: Each line contains one string
::Last line: A character ch — the letter to filter by

Output Format:
::Print all strings that start with the specified character, one per line
::The comparison should be case-insensitive
::If no strings match, print "No match found"
Constraints:
::1 ≤ n ≤ 1000
::Each string length: 1 ≤ length ≤ 100
::Only alphabets allowed in the strings (no digits or special characters for this
version)

Example1:
Input:
5
Alice
Andrew
Bob
alex
Brian
a
Output:
Alice
Andrew
alex

Example2:
Input:
4
Monica
Chandler
Ross
Rachel
z
Output:
No match found

code:
public class FindAllTheWordsBasedOnFirstLetter {

public static void printWords(String[] arr, char ch)


{
boolean flag=true;
String str = ch+"".toLowerCase();
for(String s1 : arr)
{
if(s1.toLowerCase().startsWith(str))
{
flag=false;
System.out.println(s1);
}
}
if (flag)
System.out.println("No match found");
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size=sc.nextInt();
String[] arr = new String[size];
for(int i=0;i<arr.length;i++)
arr[i]=sc.next();
char ch = sc.next().charAt(0);
printWords(arr, ch);
}
}

======================================

11]
You are building a feature for a contact management system where users search for
contacts by entering a prefix.
Your task is to write a program that takes an array of strings (names) and finds
the longest common prefix shared among all the names in the array.
If there is no common prefix, return an empty string "".

Input Format:
::The first line contains an integer n, the number of names in the array.
::The next n lines each contain a single string, representing a name.

Output Format:
::A single line containing the longest common prefix among all names.
::If there is no common prefix, output an empty string.

Constraints:
::1 ≤ n ≤ 10³
::1 ≤ length of each name ≤ 100
::The strings contain only lowercase or uppercase English alphabets.

Example1:
Input:
3
flower
flow
flight

Output:
fl

Example2:
Input:
3
dog
racecar
car

Output:

code:
public static String getPrefix1(String[] words)
{
Arrays.sort(words);// Sort and compare

String first = words[0];


String last = words[words.length-1];
int i=0;

while(i<first.length()&&i<last.length()&&first.charAt(i)==last.charAt(i))
{
i++;
}
return first.substring(0, i);
}
=================================
12]
You are given two strings s1 and s2.
Your task is to determine whether s2 is a rotation of s1.
A string s2 is considered a rotation of s1 if it can be obtained by rotating s1 at
some pivot point. That is, check if you can rotate s1 to get s2.

Input Format:
::Read two strings s1 and s2 one by one in the new line.
::1 ≤ s1.length, s2.length ≤ 1000

Output Format:
::Return "true" if s2 is a rotation of s1, otherwise return "false".

Constraints:
::The strings contain only lowercase or uppercase English letters.
::Both strings must be of the same length to be considered rotations.

Example 1:
Input:
waterbottle ABCDABCD DABC
erbottlewat
Output:
true

Example 2:
Input:
hello
lohel

Output:
true

code:
public static boolean isRotation(String str1, String str2) {

if (str1.length() != str2.length()) {
return false;
}

String concatenated = str1 + str1;

return concatenated.contains(str2);
}

======================================================
13]
You are developing a feature for a contact management application.
Users want to view contacts grouped by the length of the names, and within each
group, the names should appear in alphabetical order.

Write a program that:


::Groups all contact names that have the same length
::Sorts each group alphabetically
::Prints each group on a new line

Input Format:
::First line: An integer n — the number of contacts
::Next n lines: Each line contains a single contact name

Output Format:
::Each line contains names of the same length, sorted alphabetically and separated
by a space
::Groups can appear in any order, but names within a group must be sorted

Constraints:
::1 ≤ n ≤ 1000
::All names contain only lowercase or uppercase English alphabets
::No name is repeated

Example1:
Input :
6
apple
dog
bat
zebra
cat
go

output :
go
bat cat dog
apple zebra

code:
13. public class PrintTheStringsBasedOnLength {

public static void printStrings(String[] arr)


{
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));

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


if (arr[i]!=null) {
int len = arr[i].length();
for (int j = i; j < arr.length; j++) {
if (arr[j]!=null && arr[j].length() == len) {
System.out.print(arr[j] + " ");
arr[j] = null;
}
}
System.out.println();
}
}

}
public static void main(String[] args) {
String[] arr = {"Hello","Hi","Go", "bye", "Good"};
printStrings(arr);
String[] arr1 = {"apple","dog","bat", "zebra", "cat", "go"};
printStrings(arr1);
}
}
=================================
14]
You are developing a feature for a notes-cleaning tool where users type lists of
keywords or ideas.
Your task is to remove all duplicate words from the input string array while
preserving the original order of appearance.

Input Format:
::First line: An integer n — the number of words
::Next n lines: Each line contains a single word

Output Format:
::A single line of space-separated words, with duplicates removed and order
preserved

Constraints:
::1 ≤ n ≤ 1000
::All words consist of lowercase alphabets
::Words may be repeated multiple times

Example1:
Input :
8
note
take
note
idea
take
write
idea
plan

output :
note take idea write plan

==============================
15]
You are building an analytics tool for a chat application.
Your task is to analyze a list of words (messages or keywords) and find the word
that appears the most frequently.
If multiple words have the same highest frequency, return the one that appeared
first in the input.

Input Format:
::First line: An integer n — the number of words
::Next n lines: Each line contains a single word

Output Format:
::A single line containing the most frequent word

Constraints:
::1 ≤ n ≤ 10⁴
::Each word contains only lowercase English letters
::Words may repeat

Example1:
Input :
7
hello
world
chat
hello
world
hello
talk

output :
hello

You might also like