Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2124) Lab 2 String & Character Eng. Mohammed Abdualal
String Class In this lab, you have to be familiar how to deal with Strings. Strings : are a sequence of characters, Strings are Objects. The String class has thirteen constructors and more than forty methods Note: you have to learn almost of these constructors and methods about Strings. In this lab, we will learn an important constructors and methods and you have to be hardworking in another them. Creating Strings 1. The most direct way to create a string is to write: String greeting = "Hello world!"; 2. The most indirect way to create a string is to write: char[] helloarray = {'h', 'e', 'l', 'l', 'o', '.'; String hellostring = new String(helloArray); System.out.println(helloString); Immutable Strings A String object is immutable ; its contents cannot be changed. Does the following code change the contents of the string? String s = "Java"; s = "HTML"; The answer is no. The first statement creates a String object with the content "Java" and assigns its reference to s. The second statement creates a new String object with the content "HTML" and assigns its reference to s. The first String object still exists after the assignment, but it can no longer be accessed because variable s now points to the new object. Show below figure :
String Comparisons 1. Compare Objects in the same. The == operator as follows : if (string1 == string2) { System.out.println("string1 and string2 are the same object"); else { System.out.println("string1 and string2 are different objects"); 2. Compare of two Strings S1.equals(S2):Returns true if strings1 is equal to string S2. S1.equalsIgnoreCase(S2):Returns true if string S1 is equal to string S2 case insensitive(upper or lower). S1.compareTo(S2):Returns an integer value depends on the offset of the first two distinct characters in S1 and S2 from left to right in terms of Unicode ordering The returned value will be: 1. 0 if S1 is equal to S2. 2. >0 if S1 is greater than S2. 3. <0 if S1 is smaller than S2. S1.compareToIgnoreCase(S2):Same as compareto except that the comparison is case insensitive(upper or lower letter). TO distinguish between == Operator and equals method string. Look at the example below : String s1 = new String("Welcome to Java"); String s2 = "Welcome to Java"; System.out.println("s1==s2 is : " + (s1 == s2)); System.out.println("s1.equal(s2) is : " + (s1.equals(s2)));
When we use method intern see the result from the output code: String s1 = new String("Welcome to Java"); String s2 = "Welcome to Java"; System.out.println("s1. intern()==s2. intern() is : " + (s1.intern() == s2.intern())); System.out.println("s1.equal(s2) is : " + (s1.equals(s2))); String s1 = new String("Welcome to Java"); String s2 = "WelcOme To Java"; System.out.println("s1.equals(s2) is : " + (s1.equals(s2))); System.out.println("s1.equalsIgnoreCase(s2) is : " + (s1.equalsignorecase(s2))); System.out.println("s1.compareTo(s2) is : " + (s1.compareto(s2))); System.out.println("s1.compareToIgnoreCase(s2) is : " + (s1.comparetoignorecase(s2))); Output : String Length Returns the length of the string. String wlcmstr = "Welcome to Java II"; int len = wlcmstr.length(); System.out.println("The length of wlcmstr : "+len); Output :
s.charat(index) Method can be used to retrieve a specific character in a string s Index range from 0 to length 1 String wlcmstr = "Welcome to Java II"; System.out.println("Return the character in index 5 : "+wlcmstr.charat(5)); System.out.println("I love Palestine".charAt(10)); String Concatenation The String class includes a method for concatenating two strings: 1. Using + Operator 2. Using concat Method String s1 = "My name's "; String s2 = "Mohammed Abdual Al "; System.out.println(""+s1+" "+s2); System.out.println(""+s1.concat(s2));
Obtaining Substrings Obtain a substring from a string using the substring method in the String class. The substring method has two versions: substring(int beginindex, int endindex) Return substring begins at the specified beginindex and extends to the character at index endindex 1. substring(int beginindex) Return substring begins at the specified beginindex to the end of string. String S = "Welcome to Java"; System.out.println(S.substring(0, 11)); System.out.println(S.substring(11)); String Conversions
Finding a Character or a Substring in a String 1. public int indexof(string str) 2. (public int lastindexof(string str)) 3. public int indexof(string str, int fromindex) 4. (public int lastindexof(string str, int endindex)) Conversion Between Strings and Arrays Strings are not arrays, but a string can be converted into an array, and vice versa tochararray method : to convert String to array of character. String(char[]) method : to convert char of array(char[]) to String. Example: String S = "Welcome to Java"; char [] SCs = S.toCharArray();//To convert String to array of characters System.out.println(SCs[11]);//TO get character at index 11 from array of character SCs System.out.println(String.valueOf(SCs));//To convert array of characters to String
split(string s) Searches for a match as specified by the string argument. Example: String s = "T12009 a13 07"; String [] rstrings = s.split(" "); for (String string : rstrings) { System.out.println(string); trim() Returns a copy of this string with leading and trailing white space removed. Example: String s = " T12009 a13 07 "; System.out.println(s); System.out.println(s.trim());
touppercase() and tolowercase () Returns a copy of this string converted to lowercase or uppercase. If no conversions are necessary, these methods return the original string. Example: String s = "mohammed abdaalal"; System.out.println("toLowerCase : "+s.tolowercase()); System.out.println("toUpperCase : "+s.touppercase()); indexof () and lastindexof() Returns the index of the first (last)occurrence of the specified substring. Example: String s = "mohammed abdaalal"; System.out.println(""+s.indexOf("al")); System.out.println(""+s.lastIndexOf("al"));
StringTokenizer Class declaration StringTokenizer tokenizer = new StringTokenizer(s1); Class Methods int counttokens() This method calculates the number of times that this tokenizer's nexttoken method can be called before it generates an exception. boolean hasmoretokens() This method tests if there are more tokens available from this tokenizer's string. String nexttoken() This method returns the next token from this string tokenizer. Example :
Character Class Character class enables the char primitive data values to be treated as objects. It also contains useful methods for processing primitive values. Char charvalue =? CharValue is a character enclosed inside single quotes( ). Creating Character 1. The most direct way to create a character is to write: char ch = 'a'; // Unicode for uppercase Greek omega character char unichar = '\u039a'; // an array of chars char[] chararray ={ 'a', 'b', 'c', 'd', 'e' ; 2. The most indirect way to create a character is to write: Character ch = new Character('a'); Character ch = a ; Character Methods: Here is the list of the important instance methods that all the subclasses of the Character class implement: isletter() : Determines whether the specified char value is a letter. isdigit() : Determines whether the specified char value is a digit. iswhitespace() : Determines whether the specified char value is white space. isuppercase() : Determines whether the specified char value is uppercase. islowercase() : Determines whether the specified char value is lowercase. touppercase() : Returns the uppercase form of the specified char value. tolowercase() : Returns the lowercase form of the specified char value. tostring() : Returns a String object representing the specified character value that is, a one-character string.
Example (isletter(?)) String s = "T12009A1307"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.isletter(cs[i])){ System.out.println(""+cs[i]); Example (isdigit(?)) String s = "T12009A1307"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.isdigit(cs[i])){ System.out.print(""+cs[i]); Example (iswhitespace(?)) String s = "T12009 A13 07"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.iswhitespace(cs[i])){ System.out.println("Whitespace index : "+i);
Example (isuppercase(?) and islowercase(?)) String s = "T12009 a13 07"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if(character.isuppercase(cs[i])){ System.out.println("isUpperCase : "+cs[i]); else if(character.islowercase(cs[i])){ System.out.println("isLowerCase : "+cs[i]); Example (touppercase(?) and tolowercase(?)) String s = "T12009 a13 07"; char [] cs = s.tochararray(); for (int i = 0; i < cs.length; i++) { if (Character.isLetter(cs[i])) { System.out.println("" + Character.toUpperCase(cs[i])); System.out.println("" + Character.toLowerCase(cs[i]));
Exercises: (Please I need this homework in one file.java and send it into my email). 1. Write a method that finds the number of occurrences of a specified character in the string using the following header: public static int count(string str, char a) For example, count("welcome", 'e') returns 2. 2. Write a method that counts the number of letters in the string using the following header: public static int countletters (String s); 3. Write a method that gets the sequence numbers from the string at the same order. public static int sequencenumbers(string s); For example, sequencenumbers("moh15a8me7 Ab8luala2"); Result 158782. 4. 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. public static boolean areanagram (String s1,string s2);