Final String
Final String
Number Validation
Write a program to read a string of 10 digit number , check whether the
string contains a 10 digit number in the format XXX-XXX-XXXX where 'X' is a
digit.
Include a class UserMainCode with a static
method validateNumber which accepts a string as input .
The return type of the output should be 1 if the string meets the above
specified format . In case the number does not meet the specified format
then return -1 as output.
Create a class Main which would get the input as a String of numbers and
call the static methodvalidateNumber present in the UserMainCode.
Input and Output Format:
Input consists of a string.
Output is a string specifying the given string is valid or not .
Refer sample output for formatting specifications.
Sample Input 1:
123-456-7895
Sample Output 1:
Valid number format
Sample Input 2:
-123-12344322
Sample Output 2:
Invalid number format
importjava.util.Scanner;
publicclassUserMainCode {
staticintvalidateNumber(String s1)
{
if(s1.matches("[0-9]{3}[-]{1}[0-9]{3}[-]{1}[0-9]{4}"))
{
return 1;
}
else
return -1;
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=newScanner(System.in);
String n1=in.nextLine();
int c=UserMainCode.validateNumber(n1);
if(c==1)
System.out.println("VALID");
else
System.out.println("INVALID");
}
}
4.
Write a program to read a string of even length and to fetch two middle most
characters from the input string and return it as string output.
Include a class UserMainCode with a static method getMiddleChars which
accepts a string of even length as input . The return type is a string which
should be the middle characters of the string.
Create a class Main which would get the input as a string and call the static
method getMiddleCharspresent in the UserMainCode.
Input and Output Format:
Input consists of a string of even length.
Output is a string .
Refer sample output for formatting specifications.
Sample Input 1:
this
Sample Output 1:
hi
Sample Input 1:
Hell
Sample Output 1:
el
importjava.util.Scanner;
publicclassUserMainCode {
/**
* @paramargs
*/
staticvoidgetMiddleChars(String s1)
{
int k=s1.length();
int mid=k/2;
StringBuffersb1= newStringBuffer();
if(k%2==0)
{
sb1.append(s1.charAt(mid-1));
sb1.append(s1.charAt(mid));
}
System.out.println(sb1);
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=newScanner(System.in);
String n1=in.nextLine();
UserMainCode.getMiddleChars(n1);
}
}
/**
* @paramargs
*/
staticvoidcheckCharacters(String s1)
{
int k=s1.length();
char c=s1.charAt(0);
char d=s1.charAt(k-1);
if(c==d)
{
System.out.println("VALID");
}
else
System.out.println("INVALID");
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=newScanner(System.in);
String n1=in.nextLine();
UserMainCode.checkCharacters(n1);
}
}
Sample Input 2:
this
1
Sample Output 2:
Ts
importjava.util.Scanner;
publicclassUserMainCode {
/**
* @paramargs
*/
staticvoidcheckCharacters(String s1,int a)
{
int k=s1.length();
StringBuffer sb1= newStringBuffer();
if((2*a)<=k)
{
sb1.append(s1.substring(0,a));
sb1.append(s1.substring(k-a));
}
System.out.println(sb1);
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=newScanner(System.in);
String n1=in.nextLine();
intnum=in.nextInt();
UserMainCode.checkCharacters(n1,num);
}
}
Create a Main class which gets string as an input and call the static
method encrypt present in theUserMainCode.
Input and Output Format:
Input is a string .
Output is a string.
Sample Input 1:
curiosity
Sample Output 1:
dusipsjtz
Sample Input 2:
zzzz
Sample Output 2:
Azaz
importjava.util.Scanner;
publicclassUserMainCode {
staticvoidcheckCharacters(String s1)
{
int k=s1.length();
StringBuffer sb1= newStringBuffer();
for(inti=0;i<k;i++)
{
chard=s1.charAt(i);
if((i+1)%2!=0)
{
if(d=='z')
{
sb1.append('a');
}
else if(d=='Z')
{
sb1.append('A');
}
else
{
int c=(int)d;
++c;
sb1.append((char)c);
}
}
else
{
sb1.append(d);
}
}
System.out.println(sb1);
}
Publicstaticvoidmain(String[] args) {
// TODO Auto-generated method stub
Scanner in=newScanner(System.in);
String n1=in.nextLine();
UserMainCode.checkCharacters(n1);
}
staticvoidcheckCharacters(String s1)
{
int k=s1.length();
if((k>=6 && k<=20) && s1.matches(".*[0-9]{1}.*") &&s1.matches(".*[@$#]{1}.*"))
{
System.out.println("VALID");
}
else
System.out.println("INVALID");
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new scanner(System.in);
String n1=in.nextLine();
UserMainCode.checkCharacters(n1);
}
publicclassUserMainCode {
publicstatic String removeEvenElements(String s1)
{
StringBuffer sb1=newStringBuffer();
for(inti=0;i<s1.length();i++)
{
char k=s1.charAt(i);
if((i+1)%2!=0)
{
sb1.append(k);
}
else
{
if(k!='a'&& k!='e'&& k!='i'&& k!='o'&& k!='u'&& k!='A'&& k!='E'&& k!='I'&& k!='O'&& k!
='U')
{
sb1.append(k);
}
}
}
return sb1.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(removeEvenElements(s1));
in.close();
}
}
Sample Input 1:
ABC2012345
ABC2012660
4
Sample Output 1:
1260
Sample Input 2:
ABCDE11111
ABCDE11222
3
Sample Output 2:
333
importjava.util.Scanner;
publicclassUserMainCode {
staticintcalculateElectricityBill(String str1,String str2,int unit)
{
int e1=Integer.parseInt(str1.substring(5));
int e2=Integer.parseInt(str2.substring(5));
int total=(e2-e1)*unit;
return total;
}
{
}
}
Create a class Main which would get the input and call the static
method sumOfDigits present in the UserMainCode.
Input and Output Format:
Input consists of a string.
Output is a single integer which is the sum of digits in a given string.
Refer sample output for formatting specifications.
Sample Input 1:
good23bad4
Sample Output 1:
9
Sample Input 2:
good
Sample Output 2:
-1
importjava.util.Scanner;
publicclassUserMaincode
{
staticintsumOfDigits(String str)
{
int k=str.length();
int sum=0,i;
for(i=0;i<k;i++)
{
if(str.charAt(i)>='0'&&str.charAt(i)<='9')
{
/*StringBuffer s=newStringBuffer();
s.append(str.charAt(i));*/
sum=sum+Integer.parseInt(str.charAt(i)+);
}
}
if(sum>=0)
return sum;
else
return -1;
}
publicstaticvoid main(String args[])
{
}
}
String s1;
Scanner in=newScanner(System.in);
s1=in.nextLine();
intans=UserMaincode.sumOfDigits(s1);
System.out.println(ans);
20.String Concatenation
Write code to get two strings as input and If strings are of same length
simply append them together and return the final string. If given strings are
of different length, remove starting characters from the longer string so that
both strings are of same length then append them together and return the
final string.
Include a class UserMainCode with a static method concatstring which
accepts two string input.
The return type of the output is a string which is the concatenated string.
Create a class Main which would get the input and call the static
method concatstring present in the UserMainCode.
Input and Output Format:
Input consists of two strings.
Output is a string.
Refer sample output for formatting specifications.
Sample Input 1:
Hello
hi
Sample Output 1:
lohi
Sample Input 2:
Hello
Delhi
Sample Output 2:
HelloDelhi
importjava.util.Scanner;
public class UserMainCode {
/**
* @paramargs
*/
static String concatstring(String s1,String s2)
{
intk=s1.length();
int a=s2.length();
String s3="0";
if(k==a)
{
s3=s1.concat(s2);
}
if(k>a)
{
s3=(s1.substring(k-a).concat(s2));
}
if(k<a)
{
s3=((s1.concat(s2.substring(a-k))));
}
return s3;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
String n1=in.nextLine();
String n2=in.nextLine();
String n3=UserMainCode.concatstring(n1,n2);
System.out.println(n3);
}
}
Sample Output 2:
Invalid
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintvalidateColorCode(String s1)
{
if(s1.matches("[#]{1}[A-F|0-9]{6}"))
return 1;
else
return -1;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
int k=UserMainCode.validateColorCode(s1);
if(k==1)
System.out.println("VALID");
else
System.out.println("INVALID");
in.close();
}
}
22.Three Digits
Write a program to read a string and check if the given string is in the
format "CTS-XXX" where XXX is a three digit number.
Include a class UserMainCode with a static method validatestrings which
accepts a string. The return type (integer) should return 1 if the string format
is correct else return -1.
Create a Class Main which would be used to accept a String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a string (Valid or Invalid).
Refer sample output for formatting specifications.
Sample Input 1:
CTS-215
Sample Output 1:
Valid
Sample Input 2:
CTS-2L5
Sample Output 2:
Invalid
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintvalidatestrings(String s1)
{
if(s1.matches("(CTS)[-]{1}[0-9]{3}"))
return 1;
else
return -1;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
int k=UserMainCode.validatestrings(s1);
if(k==1)
System.out.println("VALID");
else
System.out.println("INVALID");
in.close();
}
}
Invalid
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintvalidatePassword(String s1)
{
int k=s1.length();
if(k>=8 && s1.matches(".*[@_#]{1}.*") && s1.matches("^[^@_#0-9].*") &&
s1.matches(".*[^@_#]$"))
{
}
else
return -1;
return 1;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
int k=UserMainCode.validatePassword(s1);
if(k==1)
System.out.println("VALID");
else
System.out.println("INVALID");
in.close();
}
}
28.iD Validation
Write a program to get two string inputs and validate the ID as per the
specified format.
Include a class UserMainCode with a static
method validateIDLocations which accepts two strings as input.
The return type of the output is a string Valid Id or Invalid Id.
Create a class Main which would get the input and call the static
method validateIDLocations present in the UserMainCode.
Input and Output Format:
Input consists of two strings.
First string is ID and second string is location. ID is in the format CTS-LLLXXXX where LLL is the first three letters of given location and XXXX is a four
digit number.
importjava.util.Scanner;
publicclassUserMainCode {
publicstatic String validateIDLocations(String s1,String s2)
{
if(s1.matches("(CTS)[-]{1}[a-zA-Z]{3}[-]{1}[0-9]{4}"))
{
if(s1.charAt(4)==s2.charAt(0) && s1.charAt(5)==s2.charAt(1) &&
s1.charAt(6)==s2.charAt(2))
return"valid";
}
return"invalid";
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
String s2=in.nextLine();
System.out.println(UserMainCode.validateIDLocations(s1,s2));
in.close();
}
}
29.Remove Elements
Write a program to remove all the elements of the given length and return
the size of the final array as output. If there is no element of the given
length, return the size of the same array as output.
}
}
32.IP Validator
Write a program to read a string and validate the IP address. Print Valid if
the IP address is valid, else print Invalid.
Include a class UserMainCode with a static method ipValidator which
accepts a string. The return type (integer) should return 1 if it is a valid IP
address else return 2.
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string that corresponds to an IP.
Output consists of a string(Valid or Invalid).
Refer sample output for formatting specifications.
Note: An IP address has the format a.b.c.d where a,b,c,d are numbers
between 0-255.
Sample Input 1:
132.145.184.210
Sample Output 1:
Valid
Sample Input 2:
132.145.184.290
Sample Output 2:
Invalid
importjava.util.Scanner;
importjava.util.StringTokenizer;
publicclassUserMainCode {
publicstaticStringipValidator(String s1)
{
StringTokenizerst=newStringTokenizer(s1,".");
inti=0;
while(st.hasMoreTokens())
{
int k=Integer.parseInt(st.nextToken());
if(k>=0 && k<=255)
++i;
}
if(i==4)
return"VALID";
return"Invalid";
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.ipValidator(s1));
in.close();
}
34.File Extension
Write a program to read a file name as a string and find out the file extension
and return it as output. For example, the file sun.gif has the extension gif.
Include a class UserMainCode with a static method fileIdentifier which
accepts a string. The return type (string) should return the extension of the
input string (filename).
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string that corresponds to a file name.
Output consists of a string(extension of the input string (filename)).
Refer sample output for formatting specifications.
Sample Input 1:
sun.gif
Sample Output 1:
Gif
importjava.util.Scanner;
importjava.util.StringTokenizer;
publicclassUserMainCode {
publicstaticStringipValidator(String s1)
{
StringTokenizerst=newStringTokenizer(s1,".");
st.nextToken();
String s=st.nextToken();
return s;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.ipValidator(s1));
in.close();
}
importjava.util.Scanner;
publicclassUserMainCode
{
staticintuniqueCounter(String s1,String s2)
{
inti,l=0,j;
String temp,temp1;
s1=s1.replaceAll("\\s","");
s2=s2.replaceAll("\\s","");
for(i=0;i<s1.length();i++)
{
if(i!=0)
temp=s1.substring(0,i).concat(s1.substring(i+1));
else
temp=s1.substring(i+1);
String c=s1.charAt(i)+"";
return l;
}
publicstaticvoid main(String args[])
{
Scanner in=newScanner(System.in);
String str=in.nextLine();
String str1=in.nextLine();
intans=UserMainCode.uniqueCounter(str,str1);
System.out.println(ans);
in.close();
}
36.Initial Format
Write a program to input a person's name in the format "FirstName
LastName" and return the person name in the following format - "LastName,
InitialOfFirstName".
Include a class UserMainCode with a static method nameFormatter which
accepts a string. The return type (string) should return the expected format.
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string that corresponds to a Person's name.
Output consists of a string(person's name in expected format).
Refer sample output for formatting specifications.
Sample Input :
Jessica Miller
Sample Output:
Miller, J
importjava.util.Scanner;
importjava.util.StringTokenizer;
publicclassUserMainCode {
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.nameFormatter(s1));
in.close();
}
37.Character cleaning
Write a program to input a String and a character, and remove that character
from the given String. Print the final string.
Include a class UserMainCode with a static
method removeCharacter which accepts a string and a character. The
return type (string) should return the character cleaned string.
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string and a character.
Output consists of a string(the character cleaned string).
Refer sample output for formatting specifications.
Sample Input :
elephant
e
Sample Output:
Lphant
importjava.util.Scanner;
publicclassUserMainCode {
/**
* @paramargs
*/
staticStringremoveCharacter(String s1,char s2)
{
int k=s1.length();
StringBuffer sb1= newStringBuffer();
for(inti=0;i<k;i++)
{
char c=s1.charAt(i);
if(c!=s2)
sb1.append(c);
}
return sb1.toString();
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=newScanner(System.in);
String n1=in.nextLine();
char n2=in.next().charAt(0);
String n3=UserMainCode.removeCharacter(n1,n2);
System.out.println(n3);
}
}
38.Vowel Check
Write a program to read a String and check if that String contains all
the vowels. Print yes if the string contains all vowels else print no.
Include a class UserMainCode with a static method getVowels which
accepts a string. The return type (integer) should return 1 if the String
contains all vowels else return -1.
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a string(yes or no).
Refer sample output for formatting specifications.
Sample Input 1:
abceiduosp
Sample Output 1:
yes
Sample Input 2:
bceiduosp
Sample Output 2:
No
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticStringgetVowels(String s1)
{ String s=yes;
if(s1.contains(a) && s1.contains(e) &&s1.contains(i) &&s1.contains(o) &&
s1.contains(u))
s=yes;
else
s=no;
return s;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getVowels(s1));
in.close();
}
}
39.Swap Characters
Write a program to input a String and swap the every 2 characters in the
string. If size is an odd number then keep the last letter as it is. Print the final
swapped string.
Include a class UserMainCode with a static method swapCharacter which
accepts a string. The return type (String) should return the character
swapped string.
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
TRAINER
Sample Output 1:
RTIAENR
Sample Input 2:
TOM ANDJERRY
Sample output 2:
OT MNAJDREYR
importjava.util.Scanner;
publicclassUserMainCode {
publicstatic String swapCharacter(String s1)
{
StringBuffersb=newStringBuffer();
for(inti=0;i<s1.length();i=i+2)
{ charc,d;
if(i!=s1.length()-1)
{
c=s1.charAt(i);
d=s1.charAt(i+1);
sb.append(d);
sb.append(c);
}
else
{
c=s1.charAt(i);
sb.append(c);
}
}
returnsb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.swapCharacter(s1));
in.close();
}
}
{
int c=0;
for(inti=0;i<str1.length()-1;i++)
{
if(str1.charAt(i)==str1.charAt(i+1))
{
if(str1.charAt(i+1)==str1.charAt(i+2))
{
++c;
i=i+2;
}
}
}
return c;
publicstaticvoid main(String args[])
String s1;
Scanner in=newScanner(System.in);
s1=in.nextLine();
intans=UserMainCode.countSequentialChars(s1);
System.out.println(ans);
}
}
publicclassUserMainCode {
staticintlargestChunk(String str1)
{
intc,max=0,i=0,j=0;
StringTokenizerst=newStringTokenizer(str1);
while(st.hasMoreTokens())
{
String s1=st.nextToken();
for(i=0;i<s1.length()-1;i++)
{
c=1;
if(s1.charAt(i)==s1.charAt(i+1))
{
++c;
for(j=i+2;j<s1.length();j++)
{
if(s1.charAt(i)==s1.charAt(j))
{
++c;
}
else
break;
}
}
if(c>max)
{
max=c;
i=j-1;
}
}
}
return (max);
}
{
The return type of the output is the count of all unique characters in the
strings.
Create a class Main which would get the input and call the static
method uniqueCounter present in the UserMainCode.
Input and Output Format:
Input consists a string.
Output is an integer.
Refer sample output for formatting specifications.
Sample Input 1:
HelloWorld
Sample Output 1:
5
Sample Input 2:
coco
Sample Output 2:
-1
importjava.util.Scanner;
publicclassUserMainCode
{
staticintuniqueCounter(String s)
{
inti,l=0;
String temp;
for(i=0;i<s.length();i++)
{
if(i!=0)
temp=s.substring(0,i).concat(s.substring(i+1));
else
temp=s.substring(i+1);
String c=s.charAt(i)+"";
if(!temp.contains(c))
{
++l;
}
}
return l;
}
publicstaticvoid main(String args[])
{
Scanner in=newScanner(System.in);
String str=in.nextLine();
intans=UserMainCode.uniqueCounter(str);
System.out.println(ans);
in.close();
}
45.Name Shrinking
Write a program that accepts a string as input and converts the first two
names into dot-separated initials and printa the output.
Input string format is 'fn mn ln'. Output string format is 'ln [mn's 1st
character].[fn's 1st character]'
Include a class UserMainCode with a static
method getFormatedString which accepts a string. The return type (String)
should return the shrinked name.
Create a Class Main which would be used to accept Input String and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a String.
Refer sample output for formatting specifications.
Sample Input:
Sachin Ramesh Tendulkar
Sample Output:
Tendulkar R.S
importjava.util.Scanner;
importjava.util.StringTokenizer;
publicclassUserMainCode {
publicstatic String getFormatedString(String s1)
{
StringBuffersb=newStringBuffer();
StringTokenizerst=newStringTokenizer(s1);
String s2=st.nextToken();
String s3=st.nextToken();
String s4=st.nextToken();
sb.append(s4).append(" ");
sb.append(s3.substring(0,1).toUpperCase());
sb.append(".");
sb.append(s2.substring(0,1).toUpperCase());
returnsb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getFormatedString(s1));
in.close();
}
For example, if the string is "AKj375A" then take 3+7+5=15 and not as 375
as digit.
Include a class UserMainCode with a static method oddDigitSum which
accepts a string array and the size of the array. The return type (Integer)
should return the sum.
Create a Class Main which would be used to accept Input Strings and call the
static method present in UserMainCode.
Assume maximum length of array is 20.
Input and Output Format:
Input consists of an integer n, corresponds to the number of strings, followed
by n Strings.
Output consists of an Integer.
Refer sample output for formatting specifications.
Sample Input :
3
cog2nizant1
al33k
d2t4H3r5
Sample Output :
15
(1+3+3+3+5)
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintoddDigitSum(String s1[],int k)
{
intsum=0;
for(inti=0;i<k;i++)
{
for(int j=0;j<s1[i].length();j++)
{
char c=s1[i].charAt(j);
if(c>='0'&& c<='9')
{
int x=Integer.parseInt(c+"");
if(x%2!=0)
sum=sum+x;
}
}
}
returnsum;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
int l=Integer.parseInt(in.nextLine());
String s1[]=new String[l];
for(inti=0;i<l;i++)
s1[i]=in.nextLine();
System.out.println(UserMainCode.oddDigitSum(s1,l));
in.close();
}
if(s1.matches("[#]{1}[A-F|0-9]{6}"))
return"true";
else
return"false";
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.validateColorCode(s1));
in.close();
}
}
54.Flush Characters
Write a program to read a string from the user and remove all the alphabets
and spaces from the String, and only store special characters and
digit in the output String. Print the output string.
Include a class UserMainCode with a static method getSpecialChar which
accepts a string. The return type (String) should return the character
removed string.
Create a Class Main which would be used to accept a string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a strings.
Output consists of an String (character removed string).
Refer sample output for formatting specifications.
Sample Input :
cogniz$#45Ant
Sample Output :
$#45
importjava.util.Scanner;
publicclassUserMainCode {
publicstatic String getString (String s1)
{
int x=s1.length();
StringBuffersb=newStringBuffer();
for(inti=0;i<x;i++)
{ char c=s1.charAt(i);
if((!Character.isAlphabetic(c)) && c!= )
sb.append(c);
}
returnsb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getString (s1));
in.close();
}
}
55.String Repetition
Write a program to read a string and an integer and return a string based on
the below rules.
If input2 is equal or greater than 3 then repeat the first three character of the
String by given input2 times, separated by a space.
If input2 is 2 then repeat the first two character of String two times
separated by a space,
If input2 is 1 then return the first character of the String.
Include a class UserMainCode with a static method repeatString which
takes a string & integer and returns a string based on the above rules.
Create a Class Main which would be used to accept Input string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string and integer.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
COGNIZANT
4
Sample Output 1:
COG COG COG COG
Sample Input 2:
COGNIZANT
2
Sample Output 2:
CO CO
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticStringrepeatString(String s1,int n)
{
StringBuffersb=newStringBuffer();
for(inti=0;i<n;i++)
{
if(n>=3)
sb.append(s1.substring(0,3)).append(" ");
elseif(n==2)
sb.append(s1.substring(0,2)).append(" ");
elseif(n==1)
sb.append(s1.substring(0,1));
}
returnsb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
int a=in.nextInt();
System.out.println(UserMainCode.repeatString(s1,a));
in.close();
}
}
publicclassUserMainCode {
62.Count Vowels
Given a string input, write a program to find the total number of vowels in
the given string.
Include a class UserMainCode with a static method countVowels that
accepts a String argument and returns an int that corresponds to the total
number of vowels in the given string.
Create a class Main which would get the String as input and call the static
method countVowels present in the UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of an integer..
Sample Input:
avinash
Sample Output:
3
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintcountVowels(String s1)
{
String s=s1.toLowerCase();
int c=0;
for(inti=0;i<s.length();i++)
{
char k=s.charAt(i);
if(k=='a' || k=='e' || k=='i' || k=='o' || k=='u')
++c;
}
return c;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.countVowels(s1));
in.close();
}
}
64.Reverse SubString
Given a string, startIndex and length, write a program to extract the
substring from right to left. Assume the last character has index 0.
Include a class UserMainCode with a static method reverseSubstring
that accepts 3 arguments and returns a string. The 1st argument corresponds
to the string, the second argument corresponds to the startIndex and the
third argument corresponds to the length.
Create a class Main which would get a String and 2 integers as input and call
the static method reverseSubstring present in the UserMainCode.
Input and Output Format:
The first line of the input consists of a string.
The second line of the input consists of an integer that corresponds to the
startIndex.
The third line of the input consists of an integer that corresponds to the
length of the substring.
Sample Input:
rajasthan
2
3
Sample Output:
hts
importjava.util.Scanner;
publicclassUserMainCode {
publicstatic String reverseSubstring(String s1,int n1,int n2)
{
StringBuffersb=newStringBuffer(s1);
String s=sb.reverse().toString();
returns.substring(n1,n1+n2);
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
int n11=in.nextInt();
int n21=in.nextInt();
System.out.println(UserMainCode.reverseSubstring(s1,n11,n21));
in.close();
}
}
65.String Finder
Given three strings say Searchstring, Str1 and Str2 as input, write a program
to find out if Str2 comes after Str1 in the Searchstring.
Include a class UserMainCode with a static method stringFinder that
accepts 3 String arguments and returns an integer. The 3 arguments
correspond to SearchString, Str1 and Str2. The function returns 1 if Str2
appears after Str1 in the Searchtring. Else it returns 2.
Create a class Main which would get 3 Strings as input and call the static
method stringFinder present in the UserMainCode.
Input and Output Format:
Input consists of 3 strings.
The first input corresponds to the SearchString.
The second input corresponds to Str1.
The third input corresponds to Str2.
Output consists of a string that is either yes or no
Sample Input 1:
geniousRajKumarDev
Raj
Dev
Sample Output 1:
yes
Sample Input 2:
geniousRajKumarDev
Dev
Raj
Sample Output 2:
No
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintstringFinder(String s1,String s2,String s3)
{
int l=0;
if(s1.contains(s2)&& s1.contains(s3))
{
if(s1.indexOf(s2)<s1.lastindexOf(s3))
{
l=1;
}
else
l=2;
return l;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
String s2=in.nextLine();
String s3=in.nextLine();
intans=UserMainCode.stringFinder(s1,s2,s3);
if(ans==1)
System.out.println("yes");
else
System.out.println("no");
in.close();
}
}
System.out.println("invalid");
in.close();
}
}
68.Negative String
Given a string input, write a program to replace every appearance of the
word "is" by "is not".
If the word "is" is immediately preceeded or followed by a letter no change
should be made to the string .
Include a class UserMainCode with a static method negativeString that
accepts a String arguement and returns a String.
Create a class Main which would get a String as input and call the static
method negativeString present in the UserMainCode.
Input and Output Format:
Input consists of a String.
Output consists of a String.
Sample Input 1:
This is just a misconception
Sample Output 1:
This is not just a misconception
Sample Input 2:
Today is misty
Sample Output 2:
Today is not misty
importjava.util.Scanner;
importjava.util.StringTokenizer;
publicclassUserMainCode {
publicstatic String negativeString(String s1)
{
StringBuffersb=newStringBuffer();
StringTokenizerst=newStringTokenizer(s1," ");
while(st.hasMoreTokens())
{
String s2=st.nextToken();
if(s2.equals("is"))
{
String s3=s2.replace("is", "is not");
sb.append(s3).append(" ");
}
else
{
sb.append(s2).append(" ");
}
}
returnsb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.negativeString(s1));
in.close();
}
69.Validate Number
Given a negative number as string input, write a program to validate the
number and to print the corresponding positive number.
Include a class UserMainCode with a static method validateNumber
that accepts a string argument and returns a string. If the argument string
contains a valid negative number, the method returns the corresponding
positive number as a string. Else the method returns -1.
Create a class Main which would get a String as input and call the static
method validateNumber present in the UserMainCode.
Input and Output Format:
Input consists of a String.
Output consists of a String.
Sample Input 1:
-94923
Sample Output 1:
94923
Sample Input 2:
-6t
Sample Output 2:
-1
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String validateNumber(String s1)
{
if(s1.matches("^-[0-9]*" ))
return s1.substring(1);
return"invalid";
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.validateNumber(s1));
in.close();
}
72.String Processing - IV
Write a program to read a string and also a number N. Form a new string
starting with 1st character and with every Nth character of the given string.
Ex - if N is 3, use chars 1, 3, 6, ... and so on to form the new String. Assume
N>=1.
Include a class UserMainCode with a static
method getStringUsingNthCharacter which accepts the string and the
number n. The return type is the string as per the problem statement.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a string and integer.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
HelloWorld
2
Sample Output 1:
HelWrd
import java.util.Scanner;
publicclass UserMainCode
{
static String moveX(String s1,int a)
{
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
String str=in.nextLine();
int n=in.nextInt();
System.out.println(UserMainCode.moveX(str,n));
in.close();
}
return"false";
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
String str=in.nextLine();
System.out.println(UserMainCode.checkPattern(str));
in.close();
}
}
76.String Processing
Write a program to read a string and return a new string where the first and
last chars have been interchanged.
Include a class UserMainCode with a static
method exchangeCharacters which accepts the string. The return type is
the modified string.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of string.
Refer sample output for formatting specifications.
Sample Input 1:
HelloWorld
Sample Output 1:
delloWorlH
import java.util.Scanner;
publicclass UserMainCode
{
static String checkPattern(String s1)
{
StringBuffer sb=new StringBuffer();
int x=s1.length();
sb.append(s1.charAt(x-1));
sb.append(s1.substring(1,x-1)).append(s1.charAt(0));
return sb.toString();
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
String str=in.nextLine();
System.out.println(UserMainCode.checkPattern(str));
in.close();
}
77.Regular Expression - II
Given a string (s) apply the following rules.
1. String consists of three characters only.
2. The characters should be alphabets only.
If all the conditions are satisifed then print TRUE else print FALSE.
Include a class UserMainCode with a static method validateString which
accepts the string. The return type is the boolean formed based on rules.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of TRUE or FALSE .
Refer sample output for formatting specifications.
Sample Input 1:
AcB
Sample Output 1:
TRUE
Sample Input 2:
A2B
Sample Output 2:
FALSE
import java.util.Scanner;
publicclass UserMainCode
{
static String validateString(String s1)
{
if(s1.matches("[a-zA-Z]{3}"))
return"true";
else
return"false";
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
String str=in.nextLine();
System.out.println(UserMainCode.validateString(str));
in.close();
}
}
80.String Processing - V
Write a program to read a string array, concatenate the array elements one
by one separated by comma and return the final string as output.
Include a class UserMainCode with a static method concatString which
accepts the string array. The return type is the string.
Create a Class Main which would be used to accept the string array and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of an integer n which is the number of elements followed by n
string values.
Output consists of the string.
Refer sample output for formatting specifications.
Sample Input 1:
3
AAA
BBB
CCC
Sample Output 1:
AAA,BBB,CCC
import java.util.Scanner;
publicclass UserMainCode
{
static String validateString(String s1[],int a)
{
StringBuffer sb=new StringBuffer();
for(int i=0;i<a;i++)
{
sb.append(s1[i]).append(",");
}
sb.deleteCharAt(sb.length()-1);
return sb.toString();
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
int n=Integer.parseInt(in.nextLine());
String str[]=new String[n];
for(int i=0;i<n;i++)
str[i]=in.nextLine();
System.out.println(UserMainCode.validateString(str,n));
in.close();
82.Math Calculator
Write a program that accepts three inputs, first two inputs are operands in int
form and third one being one of the following five operators: +, -, *, /, %.
Implement calculator logic and return the result of the given inputs as per
the operator provided. In case of division, Assume the result would be
integer.
Include a class UserMainCode with a static method calculator which accepts
two integers, one operand and returns the integer.
Create a Class Main which would be used to accept three integers and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of two integers and a character.
Output consists of a integer.
Refer sample output for formatting specifications.
Sample Input 1:
23
2
*
Sample Output 1:
46
import java.util.Scanner;
publicclass UserMainCode
{
staticintcalculator(int a,int b,char c)
{
int ans=0;
switch(c)
{
case'+':
ans=a+b;
break;
case'-':
ans=a-b;
break;
case'*':
ans=a*b;
break;
case'/':
ans=a/b;
break;
case'%':
ans=a%b;
break;
}
return ans;
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
int a=Integer.parseInt(in.nextLine());
int b=Integer.parseInt(in.nextLine());
char c=in.next().charAt(0);
System.out.println(UserMainCode.calculator(a,b,c));
in.close();
}
}
85.Word Count
Given a string array (s) and non negative integer (n) and return the number
of elements in the array which have same number of characters as the
givent int N.
Include a class UserMainCode with a static method countWord which
accepts the string array and integer. The return type is the string formed
based on rules.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a an integer indicating the number of elements in the string
array followed the elements and ended by the non-negative integer (N).
Output consists of a integer .
Refer sample output for formatting specifications.
Sample Input 1:
4
a
bb
b
ccc
1
Sample Output 1:
2
Sample Input 2:
5
dog
cat
monkey
bear
fox
3
Sample Output 2:
3
import java.util.Scanner;
publicclass UserMainCode
{
staticint WordCount(String s[],int x,int y)
{
int ans=0;
for(int i=0;i<x;i++)
{
if(s[i].length()==y)
{
ans++;
}
}
return ans;
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
int n=Integer.parseInt(in.nextLine());
String str[]=new String[n];
for(int i=0;i<n;i++)
str[i]=in.nextLine();
int a=Integer.parseInt(in.nextLine());
System.out.println(UserMainCode.WordCount(str,n,a));
in.close();
}
}
87.Word Count - II
Write a program to read a string and count the number of words present in it.
Include a class UserMainCode with a static method countWord which
accepts the string. The return type is the integer giving out the count of
words.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of integer.
Refer sample output for formatting specifications.
Sample Input 1:
Today is Sunday
Sample Output 1:
3
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode
{
staticint WordCount(String s)
{
StringTokenizer st=new StringTokenizer(s);
int n=st.countTokens();
return n;
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
String str=in.nextLine();
System.out.println(UserMainCode.WordCount(str));
in.close();
}
}
90.String Processing - V
Write a program to read a string and also a number N. Form a new string
made up of n repetitions of the last n characters of the String. You may
assume that n is between 1 and the length of the string.
Include a class UserMainCode with a static
method returnLastRepeatedCharacters which accepts the string and the
number n. The return type is the string as per the problem statement.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a string and integer.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
Hello
2
Sample Output 1:
lolo
Sample Input 2:
Hello
3
Sample Output 2:
llollollo
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String getString (String s1,int k)
{
int x=s1.length();
StringBuffer sb=new StringBuffer();
String s2=s1.substring(x-k);
for(int i=1;i<=k;i++)
sb.append(s2);
return sb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
int a=in.nextInt();
System.out.println(UserMainCode.getString (s1,a));
in.close();
}
}
Sample Output 2:
FALSE
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String validateString(String s1)
{
if(s1.matches("[^0-9]{1}.*"))
return"true";
return"false";
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.validateString(s1));
in.close();
}
}
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getAlternateChars(s1));
in.close();
}
}
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode {
publicstatic String getAlternateChars(String s1)
{
if(s1.charAt(0)!=@)
{
StringTokenizer st=new StringTokenizer(s1,"@");
return st.nextToken();
}
return ;
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getAlternateChars(s1));
in.close();
}
}
return"false";
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
String s2=in.nextLine();
int n=in.nextInt();
System.out.println(UserMainCode.getAlternateChars(s1,s2,n));
in.close();
}
}
1.Start Case
Write a program to read a sentence in string variable and convert the first
letter of each word to capital case. Print the final string.
Note: - Only the first letter in each word should be in capital case in final
string.
Include a class UserMainCode with a static
method printCapitalized which accepts a string. The return type (String)
should return the capitalized string.
Create a Class Main which would be used to accept a string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a strings.
Output consists of a String (capitalized string).
Refer sample output for formatting specifications.
Sample Input:
Now is the time to act!
Sample Output:
Now Is The Time To Act!
publicclass UserMainCode {
publicstatic String printCapitalized(String s1)
{
StringBuffer s5=new StringBuffer();
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens())
{
String s2=t.nextToken();
String s3=s2.substring(0,1);
String s4=s2.substring(1, s2.length());
s5.append(s3.toUpperCase()).append(s4).append(" ");
return s5.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.printCapitalized(s1));
in.close();
}
}
4.PAN Card
Write a program to read a string and validate PAN no. against following rules:
1. There must be eight characters.
2. First three letters must be alphabets followed by four digit number and
ends with alphabet
3. All alphabets should be in capital case.
Print Valid if the PAN no. is valid, else print Invalid.
Include a class UserMainCode with a static method validatePAN which
accepts a string. The return type (Integer) should return 1 if the string is a
valid PAN no. else return 2.
Create a Class Main which would be used to accept a string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string, which corresponds to the PAN number.
Output consists of a string - "Valid" or "Invalid"
Refer sample output for formatting specifications.
Sample Input 1:
ALD3245E
Sample Output 1:
Valid
Sample Input 2:
OLE124F
Sample Output 2:
Invalid
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String validatePAN(String s1)
{
if(s1.matches("[A-Z]{3}[0-9]{4}[A-Z]{1}"))
return"valid";
else
return"invalid";
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.validatePAN(s1));
in.close();
}
}
6.Test Vowels
Write a program to read a string and check if given string contains exactly
five vowels in any order. Print Yes if the condition satisfies, else print No.
Assume there is no repetition of any vowel in the given string and all
characters are lowercase.
Include a class UserMainCode with a static method testVowels which
accepts a string. The return type (Integer) should return 1 if all vowels are
present, else return 2.
Create a Class Main which would be used to accept a string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a string (Yes or No).
Refer sample output for formatting specifications.
Sample Input 1:
acbisouzze
Sample Output 1:
Yes
Sample Input 2:
cbisouzze
Sample Output 2:
No
import java.util.Scanner;
public classUserMainCode {
public static String getVowels(String s1)
{ String s=yes;
if(s1.contains(a) && s1.contains(e) && s1.contains(i) && s1.contains(o) &&
s1.contains(u))
s=yes;
else
s=no;
return s;
}
public cstatic void main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getVowels(s1));
in.close();
}
}
7.Dash Check
Write a program to read two strings and check whether or not they have
dashes in the same places. Print Yes if the condition satisfies, else print
No.
Include a class UserMainCode with a static method compareDashes which
accepts two strings. The return type (Integer) should return 1 if all dashes
are placed correctly, else return 2.
Create a Class Main which would be used to accept two strings and call the
static method present in UserMainCode.
Note: The strings must have exactly the same number of dashes in exactly
the same positions. The strings might be of different length.
Input and Output Format:
Input consists of two strings.
Output consists of a string (Yes or No).
Refer sample output for formatting specifications.
Sample Input 1:
hithere-you.
12--(134)-7539
Sample Output 1:
Yes
Sample Input 2:
-15-389
-xyw-zzy
Sample Output 2:
No
import java.util.Scanner;
public class DashCheck
{
static int compareDashes(String s1,String s2)
{
int i,j,flag=0;
for(i=0,j=0;i<s1.length()||j<s2.length();i++,j++)
{
if(i==s1.length())
{
if(s2.substring(i-1).contains("-"))
flag=1;
break;
}
if(j==s2.length())
{
if(s1.substring(j-1).contains("-"))
flag=1;
break;
}
if(s1.charAt(i)=='-')
if(s1.charAt(i)!=s2.charAt(j))
{
flag=1;
break;
}
}
if(flag==0)
return 1;
return 2;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
String s2=in.nextLine();
int b=DashCheck.compareDashes(s1,s2);
if(b==1)
System.out.println("Yes");
else
System.out.println("No");
}
8.Reverse Split
Write a program to read a string and a character, and reverse the string and
convert it in a format such that each character is separated by the given
character. Print the final string.
Include a class UserMainCode with a static method reshape which accepts
a string and a character. The return type (String) should return the final
string.
Create a Class Main which would be used to accept a string and a character,
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a string and a character.
Output consists of a string (the final string).
Refer sample output for formatting specifications.
Sample Input:
Rabbit
Sample Output:
t-i-b-b-a-R
publicclass UserMainCode {
publicstatic String reshape(String s1,char c)
{
int i;
StringBuffer sb1=new StringBuffer();
for(i=s1.length()-1;i>=0;i--)
{
sb1.append(s1.charAt(i)).append(c);
}
sb1.deleteCharAt(sb1.length()-1);
return sb1.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
char c=in.next().charAt(0);
System.out.println(UserMainCode.reshape(s1,c));
in.close();
}
}
10.Last Letters
Write a program to read a sentence as a string and store only the last letter
of each word of the sentence in capital letters separated by $. Print the final
string.
Include a class UserMainCode with a static method getLastLetter which
accepts a string. The return type (string) should return the final string.
Create a Class Main which would be used to read a string, and call the static
method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a string (the final string).
Refer sample output for formatting specifications.
Smaple Input :
This is a cat
Sample Output :
S$S$A$T
import java.util.Scanner;
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode {
publicstatic String getLastLetter(String s1)
{
StringTokenizer st=new StringTokenizer(s1);
StringBuffer sb1=new StringBuffer();
while(st.hasMoreTokens()){
String str=st.nextToken();
sb1.append(str.substring(str.length()-1).toUpperCase());
sb1.append("$");
}
sb1.deleteCharAt(sb1.length()-1);
return sb1.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.getLastLetter(s1));
in.close();
}
}
12.All Numbers
Write a program to read a string array and return 1 if all the elements of the
array are numbers, else return -1.
Include a class UserMainCode with a static method validateNumber which
accepts a string aray. The return type (integer) should be -1 or 1 based on
the above rules.
Create a Class Main which would be used to accept Input string array and call
the static method present in UserMainCode.
The string array is said to be valid if all the elements in the array are
numbers. Else it is invalid.
Input and Output Format:
Input consists of an integer specifying the size of string array followed by n
strings.
Refer sample output for formatting specifications.
Sample Input 1:
4
123
24.5
23
one
Sample Output 1:
invalid
Sample Input 2:
2
123
24.5
Sample Output 2:
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String validateNumber(String s1[],int n)
{
int l=0;
for(int i=0;i<n;i++)
{
if(s1[i].matches("[0-9.]*"))
++l;
}
if(l==n)
return"valid";
return"invalid";
}
14.Max Substring
Write a program to accept two string inputs. The first being a source string
and second one a delimiter. The source string contains the delimiter at
various locations. Your job is to return the substring with maximum number
of characters. If two or more substrings have maximim number of characters
return the substring which appears first. The size of the delimiter is 1.
Include a class UserMainCode with a static method extractMax which
accepts the string. The return type (string) should be the max substring.
Create a Class Main which would be used to accept Input string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a source string and delimiter.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
delhi-pune-patna
Sample Output 1:
Delhi\
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode {
publicstatic String extractMax(String s1,char s2)
{
String s4="";
String s=s2+" ";
StringTokenizer st=new StringTokenizer(s1,s);
int max=0;
while( st.hasMoreTokens())
{
String s3=st.nextToken();
int n=s3.length();
if(n>max)
{
max=n;
s4=s3;
}
}
return s4;
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String str=in.nextLine();
char str1=in.next().charAt(0);
System.out.println(UserMainCode.extractMax(str,str1));
in.close();
}
}
class Sample
{
static String display(HashMap<String,String> hm,String s3)
{
String str="";
String res="";
String str1="";
for(Map.Entry<String,String> map:hm.entrySet())
{
str1=map.getKey();
if(s3.equals(str1))
{
str=map.getValue();
break;
}
}
res=str+"$"+str1;
return res.toLowerCase();
}
}
public class UserMainCode
{
public static void main(String s[])
{
HashMap<String,String> l=new HashMap<String,String>();
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
l.put(sc.next(),sc.next());
}
String s2=sc.next();
System.out.println(Sample.display(l,s2));
}
22.Valid Date
Given a date string as input, write a program to validate if the given date is
in any of the following formats:
dd.mm.yyyy
dd/mm/yy
dd-mm-yyyy
Include a class UserMainCode with a static method validateDate that
accepts a String and returns an integer. This method returns 1 if the date is
valid, else return -1.
Create a class Main which would get a String as input and call the static
method validateDate present in the UserMainCode.
{
Date d3=sdf2.parse(str);
return"valid";
}
catch(ParseException e2)
{
return"invalid";
}
}
}
}
else
return invalid;
}
publicstaticvoid main(String[] args)
{
Scanner in=newScanner(System.in);
String s1=in.next();
System.out.println(UserMainCode.getvalues(s1));
}
}
23.Convert Format
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode {
publicstatic String convertFormat(String s)
{
StringTokenizer t=new StringTokenizer(s,"-");
String s1=t.nextToken();
String s2=t.nextToken();
String s3=t.nextToken();
StringBuffer sb=new StringBuffer();
sb.append(s1.substring(0, s1.length()-1)).append('-');
sb.append(s1.charAt(s1.length()-1)).append(s2.charAt(0)).append('-');
sb.append(s2.substring(1, s2.length())).append(s3.charAt(0)).append('-');
sb.append(s3.substring(1, s3.length()));
return sb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String str=in.nextLine();
System.out.println(UserMainCode.convertFormat(str));
in.close();
}
}
29.String Occurances - II
Obtain two strings S1,S2 from user as input. Your program should count the
number of times S2 appears in S1.
Return the count as output. Note - Consider case.
Include a class UserMainCode with a static method getSubstring which
accepts two string variables. The return type is the count.
Create a Class Main which would be used to accept two Input strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of two strings with maximum size of 100 characters.
Output consists of an integer.
Refer sample output for formatting specifications.
Sample Input 1:
catcowcat
cat
Sample Output 1:
2
Sample Input 2:
catcowcat
CAT
Sample Output 2:
0
import java.util.Scanner;
publicclass UserMainCode {
staticint validateNumber(String s1,String n)
{
String s=s1.replace(n,"$");
int l=0;
for(int i=0;i<s.length();i++)
if(s.charAt(i)=='$')
++l;
return l;
}
publicstaticvoid main(String[] args) {
}
}
32.Repeat Front
Given a string (s) and non negative integer (n) apply the following rules.
1.
2.
Sample Output 2:
SoSoSo
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String convertFormat(String s,int n)
{
StringBuffer sb=new StringBuffer();
for(int i=0;i<n;i++)
{
if(s.length()<3)
sb.append(s);
else
sb.append(s.substring(0,3));
}
return sb.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String str=in.nextLine();
int n=Integer.parseInt(in.nextLine());
System.out.println(UserMainCode.convertFormat(str,n));
in.close();
}
}
33.Sorted Array
Write a program to read a string array, remove duplicate elements and sort
the array.
Note:
1.
2.
string values.
Output consists of the elements of string array.
Refer sample output for formatting specifications.
Sample Input 1:
6
AAA
BBB
AAA
AAA
CCC
CCC
Sample Output 1:
AAA
BBB
CCC
Sample Input 2:
7
AAA
BBB
aaa
AAA
Abc
A
b
Sample Output 2:
A
AAA
Abc
BBB
aaa
b
import java.util.*;
{
al.add(arr[i]);
}
Iterator<String> itr=al.iterator();
arr = new String[al.size()];
int i =0 ;
while(itr.hasNext()){
arr[i++] = itr.next();
}
Arrays.sort(arr);
return arr;
}
public static void main(String[] args)
{
int n;
Scanner in = new Scanner(System.in);
n = in.nextInt();
String[] a1 = new String[n];
for(int i=0;i<n;i++)
{
a1[i] = in.next();
}
a1 = UserMainCode.orderElements(a1);
for(int i=0;i<a1.length;i++)
System.out.println(""+a1[i]);
}
}
34.Pattern Matcher
Write a program to read a string and check if it complies to the pattern 'CPTXXXXXX' where XXXXXX is a 6 digit number. If the pattern is followed, then
print TRUE else print FALSE.
Include a class UserMainCode with a static method CheckID which accepts
the string. The return type is a boolean value.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output should print TRUE or FALSE .
Refer sample output for formatting specifications.
Sample Input 1:
CPT-302020
Sample Output 1:
TRUE
Sample Input 2:
CPT123412
Sample Output 2:
FALSE
import java.util.Scanner;
publicclass UserMainCode {
staticint validateNumber(String s1)
{
if(s1.matches("(CPT-)[0-9]{6}"))
{
return 1;
}
else
return -1;
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
String n1=in.nextLine();
int c=UserMainCode.validateNumber(n1);
if(c==1)
System.out.println("VALID");
else
System.out.println("INVALID");
new String.
2. If nth character not available in a particular String in the array consider $
as the character.
3. Return the newly formed string.
Include a class UserMainCode with a static method formString which
accepts the string and integer. The return type is the string formed based on
rules.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a an integer which denotes the size of the array followed by
the array of strings and an integer (n).
Output consists of a string .
Refer sample output for formatting specifications.
Sample Input 1:
4
ABC
XYZ
EFG
MN
3
Sample Output 1:
CZG$
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String stringFinder(String s1[],int n,int a)
{
StringBuffer sb=new StringBuffer();
for(int i=0;i<n;i++)
{
if(s1[i].length()>=a)
sb.append(s1[i].substring(a-1,a));
else
}
sb.append("$");
return sb.toString();
}
publicstaticvoid main(String[] args) {
36.Regular Expression - 1
Given a string (s) apply the following rules.
1.
2.
3.
4.
If all the conditions are satisifed then print TRUE else print FALSE.
Include a class UserMainCode with a static method validate which accepts
the string. The return type is the boolean formed based on rules.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of TRUE or FALSE .
Refer sample output for formatting specifications.
Sample Input 1:
vR4u
Sample Output 1:
TRUE
Sample Input 2:
vRau
Sample Output 2:
FALSE
Sample Input 3:
vrau
Sample Output 3:
FALSE
import java.util.Scanner;
publicclass UserMainCode
{
static String checkPattern(String s1)
{
if(s1.matches("[a-zA-Z0-9]{1}[R]{1}[0-9]{1}.*") && s1.length()==4)
return"true";
return"false";
}
publicstaticvoid main(String args[])
{
Scanner in=new Scanner(System.in);
String str=in.nextLine();
System.out.println(UserMainCode.checkPattern(str));
in.close();
}
}
Sample Input 1:
23
Sample Output 1:
TRUE
Sample Input 2:
-34
Sample Output 2:
FALSE
Sample Input 3:
3a
Sample Output 3:
FALSE
AcB/TRUE
import java.util.Scanner;
publicclass UserMainCode {
static String validateNumber(String s1)
{
if(s1.matches("[0-9]*"))
{
int a=Integer.parseInt(s1);
if(a>=21 && a<=25)
return"valid";
}
return"invalid";
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
String n1=in.nextLine();
System.out.println(UserMainCode.validateNumber(n1));
return"invalid";
}
39.String Splitter
return ans;
}
40.Vowel Count
Write a program to read a string and count the number of vowels present in
it.
Include a class UserMainCode with a static method tellVowelCount which
accepts the string. The return type is the integer giving out the count of
vowels.
Note: The check is case-insensitive.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of integer.
Refer sample output for formatting specifications.
Sample Input 1:
NewYork
Sample Output 1:
2
Sample Input 2:
Elephant
Sample Output 2:
3
importjava.util.Scanner;
publicclassUserMainCode {
publicstaticintcountVowels(String s1)
{
String s=s1.toLowerCase();
int c=0;
for(inti=0;i<s.length();i++)
{
char k=s.charAt(i);
if(k=='a' || k=='e' || k=='i' || k=='o' || k=='u')
++c;
}
return c;
}
publicstaticvoid main(String[] args) {
Scanner in=newScanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.countVowels(s1));
in.close();
}
}
AAA
BB
CCCC
A
ABCDE
Sample Output 1:
a
aaa
abcde
bb
cccc
import java.util.Arrays;
import java.util.Scanner;
publicclass UserMainCode {
publicstatic String[] stringFinder(String s1[])
{
String s2[]=new String[s1.length];
for (int i = 0; i < s1.length; i++)
{
s2[i]=s1[i].toLowerCase();
}
Arrays.sort(s2);
return s2;
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
int n=Integer.parseInt(in.nextLine());
String s1[]=new String[n];
for(int i=0;i<n;i++)
s1[i]=in.nextLine();
String o[]=UserMainCode.stringFinder(s1);
for(int i=0;i<o.length;i++)
System.out.println(o[i]);
in.close();
return b;
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.scanStarNeighbors(s1));
in.close();
45.Occurance Count
Write a program to read a string that contains a sentence and read a word.
Check the number of occurances of that word in the sentence.
Include a class UserMainCode with a static method countWords which
accepts the two strings. The return type is the integer giving the count.
Note: The check is case-sensitive.
Create a Class Main which would be used to accept the two strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of two strings.
Output consists of count indicating the number of occurances.
Refer sample output for formatting specifications.
Sample Input 1:
Hello world Java is best programming language in the world
world
Sample Output 1:
2
Sample Input 2:
hello world
World
Sample Output 2:
0
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode {
publicstaticint compareDashes(String s1,String s2)
{
int ans=0;
StringTokenizer t=new StringTokenizer(s1);
while(t.hasMoreTokens())
{
String s3=t.nextToken();
if(s3.equals(s2))
ans++;
}
return ans;
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
String s2=in.nextLine();
System.out.println(UserMainCode.compareDashes(s1,s2));
in.close();
}
}
Sample Input 2:
Catcowcat
catp
Sample Output 2:
0
import java.util.Scanner;
publicclass UserMainCode {
staticint searchString(String s1,String n)
{
String s2=s1.toLowerCase();
String s3=n.toLowerCase();
String s=s2.replace(s3,"$");
int l=0;
for(int i=0;i<s.length();i++)
if(s.charAt(i)=='$')
++l;
return l;
}
publicstaticvoid main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
String n1=in.nextLine();
String n=in.nextLine();
System.out.println(UserMainCode.searchString(n1,n));
47.Strings Processing
Write a program to read a string that contains comma separated fruit names
and also a number N. Pick the nth fruit and return it. If the total number of
elements are less than the number specified in N, then return the last
element.
Include a class UserMainCode with a static method findFruitName which
accepts the the string and the number n. The return type is the string which
has the fruit name.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
48.Proper Case
Write a program to read a string and convert the intial letter of each word to
uppercase.
Include a class UserMainCode with a static method changeCase which
accepts the string. The return type is the modified string.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of a string.
Refer sample output for formatting specifications.
Sample Input 1:
This is cognizant academy
Sample Output 1:
This Is Cognizant Academy
publicclass UserMainCode {
publicstatic String printCapitalized(String s1)
{
StringBuffer s5=new StringBuffer();
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens()){
String s2=t.nextToken();
String s3=s2.substring(0,1);
String s4=s2.substring(1, s2.length());
s5.append(s3.toUpperCase()).append(s4).append(" ");
return s5.toString();
}
publicstaticvoid main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.printCapitalized(s1));
in.close();
}
}
}
}
51.Find Digits
For a given double number with atleast one decimal value, Write a program
to compute the number of digits before and after the decimal point in the
following format noOfDigitsBeforeDecimal:noOfDigitsAfterDecimal.
Note: Ignore zeroes at the end of the decimal (Except if zero is the only digit
after decimal. Refer Example 2 and 3)
Include a class UserMainCode with a static method findNoDigits which
accepts the decimal value. The return type is string.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a double.
Output consists of string.
Refer sample output for formatting specifications.
Sample Input 1:
843.21
Sample Output 1:
3:2
Sample Input 2:
20.130
Sample Output 2:
2:2
Sample Input 3:
20.130
Sample Output 3:
2:2
import java.util.Scanner;
import java.util.StringTokenizer;
publicclass UserMainCode {
static String validateNumber(double d)
{
int n1=0,n2;
String s=String.valueOf(d);
StringTokenizer t=new StringTokenizer(s,".");
String s1=t.nextToken();
String s2=t.nextToken();
n1=s1.length();
n2=s2.length();
int n3=0;
for(int i=s2.length()-1;i>=0;i--)
{
if(s2.charAt(i)==0)
++n3;
else
break;
}
if(n2!=1)
n2=n2-n3;
else
n2=1;
String s3=String.valueOf(n1)+":"+String.valueOf(n2);
return s3;
}
63.Largest Chunk
Write a program to read a string and return the length of the largest "chunk"
in the string.
A chunk is a repetition of same character 2 or more number of times. If the
given string doest not contain any repeated chunk of characters return -1.
Include a class UserMainCode with a static method getLargestSpan which
accepts the string. The return type is the integer.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of integer.
Refer sample output for formatting specifications.
Sample Input 1:
This place is soooo good
Sample Output 1:
4
importjava.util.Scanner;
importjava.util.StringTokenizer;
publicclassUserMainCode {
staticintlargestChunk(String str1)
{
intc,max=0,i=0,j=0;
StringTokenizerst=newStringTokenizer(str1);
while(st.hasMoreTokens())
{
String s1=st.nextToken();
for(i=0;i<s1.length()-1;i++)
{
c=1;
if(s1.charAt(i)==s1.charAt(i+1))
{
++c;
for(j=i+2;j<s1.length();j++)
{
if(s1.charAt(i)==s1.charAt(j))
{
++c;
}
else
break;
}
}
if(c>max)
{
max=c;
i=j-1;
}
}
}
return (max);
}
{
}
}
16/11/1991
Sample Output 1:
eligible
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
public class UserMainCode {
public static String getvalues(String str,String str1)
{
if(str.matches("[0-9]{2}[/]{1}[0-9]{2}[/]{1}[0-9]{4}"))
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String s1;
sdf.setLenient(false);
try
{
Calendar c=Calendar.getInstance();
Date d1=sdf.parse(str);
Date d2=sdf.parse(str1);
c.setTime(d1);
int y1=c.get(Calendar.YEAR);
int m1=c.get(Calendar.MONTH);
int d11=c.get(Calendar.DATE);
c.setTime(d2);
int y2=c.get(Calendar.YEAR);
int m2=c.get(Calendar.MONTH);
int d22=c.get(Calendar.DATE);
int k=Math.abs(y2-y1);
if(m1>m2)
k--;
else if(m2==m1 && d11>d22)
k--;
if(k>=18)
{
return"eligible";
}
}
catch(ParseException e)
{
return"not eligible";
}
}
return"not eligible";
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s1=in.next();
String s2="01/01/2015";
System.out.println(UserMainCode.getvalues(s1,s2));
}
}
3. Longest Word
Write a Program which finds the longest word from a sentence. Your program
should read a sentence as input from user and return the longest word. In
case there are two words of maximum length return the word which comes
first in the sentence.
Include a class UserMainCode with a static method getLargestWord which
accepts a string The return type is the longest word of type string.
Create a Class Main which would be used to accept two Input strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of a string with maximum size of 100 characters.
Output consists of a single string.
Refer sample output for formatting specifications.
Sample Input 1:
Welcome to the world of Programming
Sample Output 1:
Programming
Sample Input 2:
ABC DEF
Sample Output 2:
ABC
import java.util.*;
public class UserMainCode {
public static String lengthiestString(String s1) {
int max=0;
String s2=new String();
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens())
{
String s3=t.nextToken();
int n=s3.length();
if(n>max)
{
max=n;
s2=s3;
}
}
return s2;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(lengthiestString(s1));
}
}
4. String Occurences
Obtain two strings from user as input. Your program should count the number
of occurences of second word of second sentence in the first sentence.
Return the count as output. Note - Consider case.
Include a class UserMainCode with a static method countNoOfWords which
accepts two string variables. The return type is the modified string.
Create a Class Main which would be used to accept two Input strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of two strings with maximum size of 100 characters.
Output consists of a single string.
Refer sample output for formatting specifications.
Sample Input 1:
abc bcd abc bcd abc abc
av abc
Sample Output 1:
4
Sample Input 2:
ABC xyz AAA
w abc
Sample Output 2:
0
import java.util.Scanner;
import java.util.StringTokenizer;
public class UserMainCode {
public static void getvalues(String s1, String s2) {
int count=0;
StringTokenizer st=new StringTokenizer(s2," ");
String s3=st.nextToken();
String s4=st.nextToken();
StringTokenizer st1=new StringTokenizer(s1," ");
while(st1.hasMoreTokens())
{
String s5=st1.nextToken();
if(s4.equals(s5))
{
count++;
}
}
System.out.println(count);
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
String s2=in.nextLine();
UserMainCode.getvalues(s1,s2);
}
}
Concatenate Characters
Given an array of Strings, write a program to take the last character of each
string and make a new String by concatenating it.
Include
a
class UserMainCode with
a
static
method concatCharacter that accepts a String array as input and returns
the new String.
Create a class Main which would get the String array as input and call the
static method concatCharacterpresent in the UserMainCode.
Input and Output Format:
The first line of the input consists of an integer n that corresponds to the
number of strings in the input string array.
The next n lines of the input consist of the strings in the input string array.
Output consists of a string.
Sample Input:
3
ab
a
abcd
Sample Output:
Bad
import java.util.Scanner;
public class UserMainCode {
public static String display(String[] a)
{
StringBuffer sb=new StringBuffer();
for(int i=0;i<a.length;i++)
sb.append(a[i].charAt(a[i].length()-1));
return sb.toString();
}
public static void main(String []args){
Scanner sc=new Scanner(System.in);
int s=Integer.parseInt(sc.nextLine());
String []a=new String[s];
for(int i=0;i<s;i++)
{
a[i]=sc.nextLine();
}
System.out.println(display(a));
}
}
12.Anagram
Write a program to check whether the two given strings are anagrams.
Note: Rearranging the letters of a word or phrase to produce a new word or
phrase, using all the original letters exactly once is called Anagram."
Include a class UserMainCode with a static method getAnagram that
accepts 2 strings as arguments and returns an int. The method returns 1 if
the 2 strings are anagrams. Else it returns -1.
Create a class Main which would get 2 Strings as input and call the static
method getAnagram present in the UserMainCode.
Input and Output Format:
Input consists of 2 strings. Assume that all characters in the string are lower
case letters.
Output consists of a string that is either Anagrams or Not Anagrams.
Sample Input 1:
eleven plus two
twelve plus one
Sample Output 1:
Anagrams
Sample Input 2:
orchestra
carthorse
Sample Output 2:
Anagrams
Sample Input 3:
cognizant
technologies
Sample Output 3:
Not Anagrams
import java.util.Arrays;
import java.util.Scanner;
public class UserMainCode
{
static int getAnagram(String str1,String str2)
{
char []a1=str1.toLowerCase().replaceAll("\\s","").toCharArray();
char []a2=str2.toLowerCase().replaceAll("\\s","").toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
if(Arrays.equals(a1,a2))
return 1;
return -1;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String str1=in.nextLine();
String str2=in.nextLine();
int b=getAnagram(str1, str2);
if(b==1)
System.out.println("Anagrams");
else
System.out.println("Not Anagrams");
}
}
Sample Output:
40
import java.util.Scanner;
public class UserMainCode {
static int calculateElectricityBill(String str1,String str2)
{
int e1=Integer.parseInt(str1.substring(5));
int e2=Integer.parseInt(str2.substring(5));
int total=(e2-e1)*4;
return total;
}
{
}
}
16.Vowels
Given a String input, write a program to find the word which has the the
maximum number of vowels. If two or more words have the maximum
number of vowels, print the first word.
Include a class UserMainCode with a static method
storeMaxVowelWord that accepts a string argument and returns the
word containing the maximum number of vowels.
Create a class Main which would get the a String as input and call the static
method storeMaxVowelWord present in the UserMainCode.
Input and Output Format:
Input consists of a string. The string may contain both lower case and upper
case letters.
Output consists of a string.
Sample Input :
What is your name?
Sample Output :
your
import java.util.Scanner;
import java.util.StringTokenizer;
public class UserMainCode {
public static String lengthiestString(String s1) {
int max=0;
String s2=new String();
StringTokenizer t=new StringTokenizer(s1," ");
while(t.hasMoreTokens())
{
String s5=t.nextToken();
int n=0;
for (int i = 0; i < s5.length(); i++) {
if (s5.charAt(i) == 'a' || s5.charAt(i) == 'e'|| s5.charAt(i) == 'i' || s5.charAt(i) == 'o'||
s5.charAt(i) == 'u'
||s5.charAt(i) == 'A' ||s5.charAt(i) == 'E' ||s5.charAt(i) == 'I' ||s5.charAt(i) == 'O' ||
s5.charAt(i) == 'U')
n++;
}
if(n>max)
{
max=n;
s2=s5;
}
}
return s2;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(lengthiestString(s1));
}
20.Largest Span
Write a program to read an array and find the size of largest span in the
given array
""span"" is the number of elements between two repeated numbers
including both numbers. An array with single element has a span of 1.
.
Include a class UserMainCode with a static method getMaxSpan which
accepts a single integer array. The return type (integer) should be the size of
largest span.
Create a Class Main which would be used to accept Input array and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of n+1 integers. The first integer corresponds to n, the number
of elements in the array. The next 'n' integers correspond to the elements in
the array.
Output consists of a single Integer.
Refer sample output for formatting specifications.
Assume that the maximum number of elements in the array is 20.
Sample Input 1:
5
1
2
1
1
3
Sample Output 1:
4
Sample Input 2:
7
1
4
2
1
4
1
5
Sample Output 2:
6
import java.util.Scanner;
public class UserMainCode
{
static int getMaxSpan(int ar[])
{
String str="";
int max=0;
for(int a:ar)
str=str+a;
for(int i=0;i<str.length();i++)
{
int k=str.lastIndexOf(str.charAt(i));
int l=str.indexOf(str.charAt(i));
int span=k-l+1;
if(span>max)
max=span;
}
return max;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=in.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++)
a[i]=in.nextInt();
System.out.println(getMaxSpan(a));
}
}
21.Max Scorer
Write a program that performs the following actions:
1. Read n strings as input and stores them as an arraylist. The string
consists of student information like name and obtained marks of three
subjects. Eg: name-mark1-mark2-mark3 [suresh-70-47-12] The mark
would range between 0 100 (inclusive).
2. Write a function highestScorer which accepts these the arraylist and
returns the name of the student who has scored the max marks.
Assume the result will have only one student with max mark.
Include a class UserMainCode with the static method highestScorer which
accepts the arraylist and returns the name (string) of max scorer.
Create a Class Main which would be used to read n strings into arraylist and
call the static method present in UserMainCode.
Input and Output Format:
Input consists of 1 integer and n strings. The first integer denotes the size of
the arraylist, the next n strings are score pattern described above.
Output consists of a string with the name of the top scorer.
Refer sample output for formatting specifications.
Sample Input 1:
3
sunil-56-88-23
bindul-88-70-10
john-70-49-65
Sample Output 1:
John
import java.util.Scanner;
import java.util.StringTokenizer;
{
StringTokenizer st=new StringTokenizer(ar[i],"-");
String tname=st.nextToken();
int tscore=0;
for(int j=0;j<3;j++)
tscore=tscore+Integer.parseInt(st.nextToken());
if(tscore>score)
{
score=tscore;
name=tname;
}
}
return name;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=Integer.parseInt(in.nextLine());
String a[]=new String[n];
for(int i=0;i<n;i++)
a[i]=in.nextLine();
System.out.println(highestScorer(a));
}
}
22.Max Vowels
Write a Program which fetches the word with maximum number of vowels.
Your program should read a sentence as input from user and return the word
with max number of vowels. In case there are two words of maximum length
return the word which comes first in the sentence.
Include a class UserMainCode with a static
method getWordWithMaximumVowels which accepts a string The return
type is the longest word of type string.
Create a Class Main which would be used to accept two Input strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of a string with maximum size of 100 characters.
Output consists of a single string.
Refer sample output for formatting specifications.
Sample Input 1:
Appreciation is the best way to motivate
Sample Output 1:
Appreciation
import java.util.Scanner;
import java.util.StringTokenizer;
public class UserMainCode {
if(n>max)
{
max=n;
s2=s5;
}
}
return s2;
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(lengthiestString(s1));
}
24.Adjacent Swaps
Write a Program that accepts a string as a parameter and returns the string
with each pair of adjacent letters reversed. If the string has an odd number
of letters, the last letter is unchanged.
Include a class UserMainCode with a static method swapPairs which accepts
a string. The return type is string which is reversed pair of letters.
Create a Class Main which would be used to accept two Input strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of a string with maximum size of 100 characters.
Output consists of a single string.
Refer sample output for formatting specifications.
Sample Input 1:
forget
Sample Output 1:
ofgrte
Sample Input 2:
New York
Sample Output 2:
eN woYkr
import java.util.Scanner;
public class UserMainCode {
public static String swapCharacter(String s1)
{
StringBuffer sb=new StringBuffer();
for(int i=0;i<s1.length();i=i+2)
{ char c,d;
if(i!=s1.length()-1)
{
c=s1.charAt(i);
d=s1.charAt(i+1);
sb.append(d);
sb.append(c);
}
else
{
c=s1.charAt(i);
sb.append(c);
}
}
return sb.toString();
}
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
String s1=in.nextLine();
System.out.println(UserMainCode.swapCharacter(s1));
in.close();
}
26.Password
Given a String , write a program to find whether it is a valid password or not.
Validation Rule:
Atleast 8 characters
Atleast 1 number(1,2,3...)
Atleast 1 special character(@,#,%...)
Atleast 1 alphabet(a,B...)
Include a class UserMainCode with a static method validatePassword
that accepts a String argument and returns a boolean value. The method
returns true if the password is acceptable. Else the method returns false.
Create a class Main which would get a String as input and call the static
method validatePassword present in the UserMainCode.
Input and Output Format:
Input consists of a String.
Output consists of a String that is either Valid or Invalid.
Sample Input 1:
cts@1010
Sample Output 1:
Valid
Sample Input 2:
punitha3
Sample Output 2:
Invalid
import java.util.Scanner;
public class UserMainCode
{
static int passwordValidation(String s)
{
if(s.length()>=8&&s.matches(".*[a-zA-Z].*")&&s.matches(".*[09].*")&&s.matches(".*[^0-9A-Za-z].*"))
return 1;
return -1;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s=in.nextLine();
int b=UserMainCode.passwordValidation(s);
if(b==1)
System.out.println("valid");
else
System.out.println("invalid");
}
}
30.Anagrams
Write a program to read two strings and checks if one is an anagram of the
other.
An anagram is a word or a phrase that can be created by rearranging the
letters of another given word or phrase. We ignore white spaces and letter
case. All letters of 'Desperation' can be rearranged to the phrase 'A Rope
Ends It'.
Include a class UserMainCode with a static method checkAnagram which
accepts the two strings. The return type is boolean which is TRUE / FALSE.
Create a Class Main which would be used to accept the two strings and call
the static method present in UserMainCode.
Input and Output Format:
Input consists of two strings.
Output consists of TRUE / FALSE.
Refer sample output for formatting specifications.
Sample Input 1:
tea
eat
Sample Output 1:
TRUE
Sample Input 2:
Desperation
A Rope Ends It
Sample Output 2:
TRUE
import java.util.Arrays;
import java.util.Scanner;
public class UserMainCode
{
static int getAnagram(String str1,String str2)
{
char []a1=str1.toLowerCase().replaceAll("\\s","").toCharArray();
char []a2=str2.toLowerCase().replaceAll("\\s","").toCharArray();
Arrays.sort(a1);
Arrays.sort(a2);
if(Arrays.equals(a1,a2))
return 1;
return -1;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String str1=in.nextLine();
String str2=in.nextLine();
int b=getAnagram(str1, str2);
if(b==1)
System.out.println("TRUE");
else
System.out.println("FALSE");
}
}
32.Word Count
Given a string array (s) with each element in the array containing alphabets
or digits. Write a program to add all the digits in every string and return the
sum as an integer. If two digits appear simultaneously do not consider it as
one number. Ex- For 'Hyderabad 21' consider 2 and 1 as two digits instead of
21 as a number.
Include a class UserMainCode with a static method sumOfDigits which
accepts the string array. The return type is the integer formed based on
rules.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a an integer indicating the number of elements in the string
array.
Output consists of a integer .
Refer sample output for formatting specifications.
Sample Input 1:
5
AAA1
B2B
4CCC
A5
ABCDE
Sample Output 1:
12
Sample Input 2:
3
12
C23
5CR2
Sample Output 2:
15
import java.util.Scanner;
public class UserMainCode
{
static int sumOfDigits(String str[])
{
int sum=0,i;
for(int j=0;j<str.length;j++)
{
for(i=0;i<str[j].length();i++)
{
if(str[j].charAt(i)>='0'&&str[j].charAt(i)<='9')
{
sum=sum+Integer.parseInt(str[j].charAt(i)+"");
}
}
}
if(sum>=0)
return sum;
return -1;
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
int n1=Integer.parseInt(in.nextLine());
String s1[]=new String[n1];
for(int i=0;i<n1;i++)
s1[i]=in.nextLine();
int ans=UserMainCode.sumOfDigits(s1);
System.out.println(ans);
}
}
33.Prefix Finder
Given a string array (s) with each element in the array containing 0s and 1s.
Write a program to get the number of strings in the array where one String is
getting as prefixed in other String in that array .
Example 1: Input: {10,101010,10001,1111} Output =2 (Since 10 is a prefix
of 101010 and 10001)
Example 2: Input: {010,1010,01,0111,10,10} Output =3(01 is a prefix of 010
and 0111. Also, 10 is a prefix of 1010) Note: 10 is NOT a prefix for 10.
Include a class UserMainCode with a static method findPrefix which accepts
the string array. The return type is the integer formed based on rules.
Create a Class Main which would be used to accept the string and integer
and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a an integer indicating the number of elements in the string
array followed by the array.
Output consists of a integer .
Refer sample output for formatting specifications.
Sample Input 1:
4
0
1
11
110
Sample Output 1:
3
import java.util.Scanner;
public class PrefixFinder
{
public static int findPrefix(String s[])
{
int count=0;
for(int i=0;i<s.length;i++)
{
int c=1;
for(int j=0;j<s.length;j++)
{
if(s[j].matches("^"+s[i]+"[10]{1,}"))
c++;
}
if(c>count)
count=c;
}
return count;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=Integer.parseInt(in.nextLine());
String[] a=new String[n];
for(int i=0;i<n;i++)
a[i]=in.nextLine();
System.out.println(PrefixFinder.findPrefix(a));
}
}
34.Commons
Given two arrays of strings,return the count of strings which is common in
both arrays. Duplicate entries are counted only once.
Include a class UserMainCode with a static
method countCommonStrings which accepts the string arrays. The return
type is the integer formed based on rules.
Create a Class Main which would be used to accept the string arrays and
integer and call the static method present in UserMainCode.
Input and Output Format:
Input consists of a an integer indicating the number of elements in the string
for(int i=0;i<s1.length;i++)
{
for(int j=0;j<s2.length;j++)
{
if(s1[i].equals(s2[j]))
count++;
}
}
return count;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n=Integer.parseInt(in.nextLine());
String[] a1=new String[n];
for(int i=0;i<n;i++)
a1[i]=in.nextLine();
n=Integer.parseInt(in.nextLine());
String[] a2=new String[n];
for(int i=0;i<n;i++)
a2[i]=in.nextLine();
System.out.println(countCommon(a1,a2));
}
}
36.E-Mail Validation
Write a program to read a string and validate the given email-id as input.
Validation Rules:
1. Ensure that there are atleast 5 characters between '@' and '.'
2. There should be only one '.' and one '@' symbol.
3. The '.' should be after the '@' symbol.
4. There must be atleast three characters before '@'.
5. The string after '.' should only be 'com'
Include a class UserMainCode with a static method ValidateEmail which
accepts the string. The return type is TRUE / FALSE as per problem.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of TRUE / FALSE.
Refer sample output for formatting specifications.
Sample Input 1:
test@gmail.com
Sample Output 1:
TRUE
Sample Input 2:
academy@xyz.com
Sample Output 2:
FALSE
import java.util.Scanner;
public class UserMainCode
{
static boolean validateEmail(String str)
{
return str.matches("[a-zA-Z0-9]{3}@[a-zA-Z]{5}\\.com");
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s=in.nextLine();
System.out.println((validateEmail(s)+"").toUpperCase());
}
}
40.ISBN Validation
Write a program to read a string and validate the given ISBN as input.
Validation Rules:
1. An ISBN (International Standard Book Number) is a ten digit code which
uniquely identifies a book.
2. To verify an ISBN you calculate 10 times the first digit, plus 9 times the
second digit, plus 8 times the third ..all the way until you add 1 times the last
digit.
If the final number leaves no remainder when divided by 11 the code is a
valid ISBN.
Example 1:
Input:0201103311
Calculation: 10*0 + 9*2 + 8*0 + 7*1 + 6*1 + 5*0 + 4*3 + 3*3 + 2*1 + 1*1
= 55.
55 mod 11 = 0
Hence the input is a valid ISBN number
Output: true
Include a class UserMainCode with a static method validateISBN which
accepts the string. The return type is TRUE / FALSE as per problem.
Create a Class Main which would be used to accept the string and call the
static method present in UserMainCode.
Input and Output Format:
Input consists of a string.
Output consists of TRUE / FALSE.
Refer sample output for formatting specifications.
Sample Input 1:
0201103311
Sample Output 1:
TRUE
import java.util.Scanner;
public class UserMainCode
{
static boolean validateISBN(String str)
{
if(str.matches("[0-9]{10}"))
{
int i=10,sum=0;
for(int j=0;j<10;j++,i--)
sum=sum+i*Integer.parseInt(str.charAt(j)+"");
if(sum%11==0)
return true;
}
return false;
}
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
String s=in.nextLine();
System.out.println((validateISBN(s)+"").toUpperCase());
}
}