0% found this document useful (0 votes)
99 views11 pages

2.tushar - Assignment 2

The document discusses arrays, strings, and regular expressions. It provides examples of methods to get the second smallest element in an array, check if strings are anagrams by sorting and comparing characters, and validate usernames with regular expressions. It includes sample code to implement these examples and questions to test understanding of string and regex concepts like character classes, indexes, metacharacters, and quantifiers.

Uploaded by

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

2.tushar - Assignment 2

The document discusses arrays, strings, and regular expressions. It provides examples of methods to get the second smallest element in an array, check if strings are anagrams by sorting and comparing characters, and validate usernames with regular expressions. It includes sample code to implement these examples and questions to test understanding of string and regex concepts like character classes, indexes, metacharacters, and quantifiers.

Uploaded by

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

Assignmet-2(Array , Regular Expression and Strings)

Array:
Exercise 1: Create a method which accepts an array of integer elements and return the second smallest
element in the array

Method Name getSecondSmallest

Method Description Get the second smallest element in the array

Argument int[]

Return Type int

Logic Sort the array and return the second smallest


element in the array

ANSWER: public class getSecondSmallest{  
public static int getSecondSmallest(int[] a, int total){  
int temp;  
for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
       }    }     }  
                            return a[1];//2nd element because index starts from 0  
}  
public static void main(String args[]){  
int a[]={1,2,5,6,3,2};  
int b[]={44,66,99,77,313,22,55};  
System.out.println("Second smallest: "+getSecondSmallest(a,6));  
System.out.println("Second smallest: "+getSecondSmallest(b,7));  
}}  
OUTPUT: Second smallest: 2 Second smallest: 44
Strings:
Questions and Exercises: Characters and Strings

Questions
1. What is the initial capacity of the following string builder?

StringBuildersb = new StringBuilder("Able was I ere I saw Elba.");


Answer: It's the length of the initial string + 16: 26 + 16 = 42.

2. Consider the following string:

String hannah = "Did Hannah see bees? Hannah did.";

a. What is the value displayed by the expression hannah.length()?Answer: 32.

b. What is the value returned by the method call hannah.charAt(12)? Answer: e.

c. Write an expression that refers to the letter b in the string referred to by hannah.

Answer: hannah.charAt(15).

3. How long is the string returned by the following expression? What is the string?

"Was it a car or a cat I saw?".substring(9, 12)


Answer: It's 3 characters in length: car. It does not include the space after car.

4. In the following program, called ComputeResult, what is the value of result after each numbered line
executes?

public class ComputeResult {


public static void main(String[] args) {
String original = "software";
StringBuilder result = new StringBuilder("hi");
int index = original.indexOf('a');

/*1*/ result.setCharAt(0, original.charAt(0));


/*2*/ result.setCharAt(1, original.charAt(original.length()-1));
/*3*/ result.insert(1, original.charAt(4));
/*4*/ result.append(original.substring(1,4));
/*5*/ result.insert(3, (original.substring(index, index+2) + " "));

System.out.println(result);
}
}
Answer:
si
se
swe
sweoft
swear oft

Exercises
1. Show two ways to concatenate the following two strings together to get the string "Hi, mom.":

String hi = "Hi, ";


String mom = "mom.";
Answer: hi.concat(mom) and hi + mom.

2. Write a program that computes your initials from your full name and displays them.

Answer: ComputeInitials

public class ComputeInitials {

public static void main(String[] args) {

String myName = "Fred F. Flintstone";

StringBuffer myInitials = new StringBuffer();

int length = myName.length();

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

if (Character.isUpperCase(myName.charAt(i))) {

myInitials.append(myName.charAt(i));

System.out.println("My initials are: " + myInitials);

An anagram is a word or a phrase made by transposing the letters of another word or phrase; for example,
"parliament" is an anagram of "partial men," and "software" is an anagram of "swear oft." Write a program that
figures out whether one string is an anagram of another string. The program should ignore white space and
punctuation.
Answer: Anagram
public class Anagram {

public static boolean areAnagrams(String string1,


String string2) {

String workingCopy1 = removeJunk(string1);


String workingCopy2 = removeJunk(string2);

workingCopy1 = workingCopy1.toLowerCase();
workingCopy2 = workingCopy2.toLowerCase();

workingCopy1 = sort(workingCopy1);
workingCopy2 = sort(workingCopy2);

return workingCopy1.equals(workingCopy2);
}

protected static String removeJunk(String string) {


int i, len = string.length();
StringBuilder dest = new StringBuilder(len);
char c;

for (i = (len - 1); i >= 0; i--) {


c = string.charAt(i);
if (Character.isLetter(c)) {
dest.append(c);
}
}

return dest.toString();
}
protected static String sort(String string) {
char[] charArray = string.toCharArray();

java.util.Arrays.sort(charArray);

return new String(charArray);


}

public static void main(String[] args) {


String string1 = "Cosmo and Laine:";
String string2 = "Maid, clean soon!";

System.out.println();
System.out.println("Testing whether the following "
+ "strings are anagrams:");
System.out.println(" String 1: " + string1);
System.out.println(" String 2: " + string2);
System.out.println();

if (areAnagrams(string1, string2)) {
System.out.println("They ARE anagrams!");
} else {
System.out.println("They are NOT anagrams!");
}
System.out.println();
}
}

Regular Expression:
Questions

1. What are the three public classes in the java.util.regex package? Describe the purpose of each.

Answer: Pattern instances are compiled representations of regular expressions.


Matcher instances are engines that interpret patterns and perform match operations against input
strings.

PatternSyntaxException defines an unchecked exception indicating a syntax error in a regular


expression.

2. Consider the string literal "foo". What is the start index? What is the end index? Explain what these
numbers mean.

Answer: Each character in the string resides in its own cell. Index positions point between cells. The
string "foo" starts at index 0 and ends at index 3, even though the characters only occupy cells 0, 1,
and 2.

3. What is the difference between an ordinary character and a metacharacter? Give an example of each.

Answer:An ordinary character in a regular expression matches itself. A metacharacter is a special


character that affects the way a pattern is matched. The letter A is an ordinary character. The
punctuation mark . is a metacharacter that matches any single character.

4. How do you force a metacharacter to act like an ordinary character?

Answer: There are two ways:

Precede the metacharacter with a backslash (\);

Enclose the metacharacter within the quote expressions, \Q (at the beginning) and \E (at the end).

5. What do you call a set of characters enclosed in square brackets? What is it for?

Answer: This is a character class. It matches any single character that is in the class of characters
specified by the expression between the brackets.

6. Here are three predefined character classes: \d, \s, and \w. Describe each one, and rewrite it using
square brackets.

Answer:

\d Matches any digit. [0-9]

\s Matches any white space character. [ \t\n-x0B\f\r]

\w Matches any word character. [a-zA-Z_0-9]

7. For each of \d, \s, and \w, write two simple expressions that match the opposite set of characters.

Answer:

\d \D [^\d]

\s \S [^\s]
\w \W [^\w]

8. Consider the regular expression (dog){3}. Identify the two subexpressions. What string does the
expression match?

Answer: The expression consists of a capturing group, (dog), followed by a greedy quantifier {3}. It
matches the string "dogdogdog"

Ex-1
Write a programe to validate a user name. The regular expression pattern allows lower
case alphanumeric characters, allows '-', '_'. Incase if you want to support uppercase
characters then regular expression should be ^[a-zA-Z0-9_-]{6,14}$

Expected output:

Is 'java2novice' a valid user name? true


Is 'cric' a valid user name? false
Is 'JAVA2NOVICE' a valid user name? false
Is 'java.2.novice' a valid user name? false
Is 'java_2-novice' a valid user name? true
package ASSIGNMENT;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class regular {

public static boolean isValidUsername(String name)


{

String regex = "^[a-zA-Z0-9_-]{6,14}$";

Pattern p = Pattern.compile(regex);

if (name == null) {
return false;
}

Matcher m = p.matcher(name);
return m.matches();
}

public static void main(String[] args)


{

String str1 = "java2novice";


System.out.println(isValidUsername(str1));

String str3 = "cric";


System.out.println(isValidUsername(str3));

String str4 = " JAVA2NOVICE ";


System.out.println(isValidUsername(str4));

String str5 = "java.2.novice";


System.out.println(isValidUsername(str5));

String str6 = "java_2-novice";


System.out.println(isValidUsername(str6));
}
}

Ex-2:

to validate a email address using regular expression.

Expected output:

Is '[email protected]' a valid email address? True

Is 'cric*7*&@yahoo.com' a valid email address? False

Is 'JAVA2NOVICE.gmail.com' a valid email address? false

package ASSIGNMENT;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;
public class email1 {
public static boolean isValid(String email)
{
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+
"[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";

Pattern pat = Pattern.compile(emailRegex);


if (email == null)
return false;
return pat.matcher(email).matches();
}

public static void main(String[] args)


{
ArrayList<String> address = new ArrayList<>();

address.add("[email protected]");
address.add(" cric*7*&@yahoo.com");
address.add("JAVA2NOVICE.gmail.com");

for(String i : address){
if (isValid(i))
System.out.println(i + " - Yes");
else
System.out.println(i + " - No");
}
}
}

Ex-3:
to validate a password using regular expression. Here this regular expression allows
must contain one digit, one lower case char, one upper case char, some special chars,
length should be within 6 to 15 chars.
Is 'java2novice' a valid password? False
Is 'gabbarsingh' a valid password? false
Is 'Java2NOVICE$' a valid password? true
Is '234aBc#' a valid password? true
package ASSIGNMENT;

import java.util.regex.*;
public class password {

// Function to validate the password.


public static boolean
isValidPassword(String password)
{

// Regex to check valid password.


String regex = "^(?=.*[0-9])"
+ "(?=.*[a-z])(?=.*[A-Z])"
+ "(?=.*[@#$%^&+=])"
+ "(?=\\S+$).{8,20}$";

// Compile the ReGex


Pattern p = Pattern.compile(regex);

// If the password is empty


// return false
if (password == null) {
return false;
}

// Pattern class contains matcher() method


// to find matching between given password
// and regular expression.
Matcher m = p.matcher(password);

// Return if the password


// matched the ReGex
return m.matches();
}

// Driver Code.
public static void main(String args[])
{

// Test Case 1:
String str1 = "java2novice";
System.out.println(isValidPassword(str1));

// Test Case 2:
String str2 = "gabbarsingh";
System.out.println(isValidPassword(str2));

// Test Case 3:
String str3 = "Java2NOVICE$";
System.out.println(isValidPassword(str3));

// Test Case 4:
String str4 = "A234aBc#";
System.out.println(isValidPassword(str4));

}
}

You might also like