java String_program_day1[2]
java String_program_day1[2]
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).
Output Format:-
-->Output a single line containing the reversed string.
Constraints
-->1 ≤ len(message) ≤ 1000
Example1:
Input : Hello, World!
output: !dlroW ,olleH
Code:
-----------------------------------------------------------------------------------
--------------------------------
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.
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;
-----------------------------------------------------------------------------------
---------------------------------
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).
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
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.
A string is considered valid when it contains an equal number of '*' and '#'
characters.
Task:
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:
1 ≤ length of S ≤ 1000
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;
}
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]
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 {
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
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 {
-----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
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.
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 {
======================================
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
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;
}
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.
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 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