Presentation is loading. Please wait.

Presentation is loading. Please wait.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 1 Chapter 9 Characters and Strings (sections 9.1-9.2,

Similar presentations


Presentation on theme: "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 1 Chapter 9 Characters and Strings (sections 9.1-9.2,"— Presentation transcript:

1 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 1 Chapter 9 Characters and Strings (sections 9.1-9.2, 9.5-9.6) StringTokenizer (not in text)

2 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 2 Characters In Java, single characters are represented using the primitive data type char. Character literals (constants) are written as symbols enclosed in single quotes. –'a' 'B' ':' '\n' Characters are stored in a computer memory as integers using some form of encoding. –ASCII, which stands for American Standard Code for Information Interchange, is the document coding schemes most widely used today. –Java uses Unicode (which includes ASCII) for representing char constants.

3 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 3 ASCII Encoding For example, character 'O' is 79 (row value 70 + col value 9 = 79). O 9 7070

4 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 4 Using the char type Since a character is stored as an integer, char variables can be used like integers when appropriate. –You can use a char as the test variable in a switch statement –You can compare char values using the relational operators You can take the difference between two characters int digit = digitChar - '0'; int letterIndex = letter - 'a';

5 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 5 Character Processing Declaration and initialization char ch1, ch2 = ‘X’; Type conversion between int and char. System.out.print("ASCII code of character X is " + (int) 'X' ); System.out.print("Character with ASCII code 88 is " + (char)88 ); This comparison returns true because ASCII value of 'A' is 65 while that of 'c' is 99. ‘A’ < ‘c’ Use the charAt method of the String class to get individual characters from a String. String word = kbd.nextLine(); char first = word.charAt(0);

6 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 6 Console menu do { printMenu(); input = instream.next( ); switch (input.charAt(0)) { case 'a': methodA(); break; … case 'q': System.exit(0); break; } } while (true);

7 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 7 Character Class Like the other primitive types, there is a wrapper class (in java.lang) for the char type. Useful Methods charValue( ) returns a char that is the value stored in the Character getNumericValue( ) returns the Unicode value for the char

8 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 8 Static Character Methods These are all called with Character. in front of the name boolean methods isDigit( char) isLetter( char) isWhitespace( char) isUpperCase( char) isLowerCase(char) other methods char toLowerCase( char) char toUpperCase( char)

9 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 9 More about Strings A string is a sequence of characters that is treated as a single object. Instances of the String class are used to represent strings in Java. We can access individual characters of a string by calling the charAt method of the String object. –You can use a loop to process each character in the String

10 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 10 Accessing Individual Elements Individual characters in a String accessed with the charAt method. 012345 6 Sumatr a String name = "Sumatra"; name This variable refers to the whole string. name.charAt( 3 ) The method returns the character at position # 3.

11 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 11 Example: Counting Vowels char letter; String name = JOptionPane.showInputDialog(null,"Your name:"); int numberOfCharacters = name.length(); int vowelCount= 0; for (int i = 0; i < numberOfCharacters; i++) { letter = name.charAt(i); if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { vowelCount++; } System.out.print(name + ", your name has " + vowelCount + " vowels"); Here’s the code to count the number of vowels in the input string.

12 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 12 Example: Counting ‘Java’ int javaCount = 0; boolean repeat = true; String word; while ( repeat ) { word = JOptionPane.showInputDialog(null,"Next word:"); if ( word.equals("STOP") ) { repeat = false; } else if ( word.equalsIgnoreCase("Java") ) { javaCount++; } Continue reading words and count how many times the word Java occurs in the input, ignoring the case. Notice how the comparison is done. We are not using the == operator.

13 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 13 Other Useful String Operators Returns true if a string ends with a specified suffix string. str1.endsWith( str2 ) Returns true if a string starts with a specified prefix string. str1.startsWith( str2 ) Converts a given primitive data value to a string. String.valueOf( 123.4565 ) Removes the leading and trailing spaces. str1.trim( ) Extracts the a substring from a string. str1.substring( 1, 4 ) Compares the two strings. str1.compareTo( str2 ) Meaning endsWith startsWith valueOf trim substring compareTo Method And many more … See the String class documentation for details.

14 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 14 String Methods that use char A char can be added to a String String plural = word + 's'; *String valueOf( char ch) *String replace( char oldChar, char newChar) *int indexOf( char ch) *int indexOf( char ch, int fromIndex) *int lastIndexOf( char ch) *int lastIndexOf( char ch, int fromIndex)

15 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 15 The String Class is Immutable In Java a String object is immutable –This means once a String object is created, it cannot be changed, to replace a character with another character or remove a character, a new String object has to be created –None of the String methods change the original string. They often createand return a new string. For example, substring creates a new string from a given string. The String class is defined in this manner for efficiency reasons.

16 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 16 Creating String Objects We can do this because String objects are immutable.

17 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 17 Effect of Immutability When you need to change a String, you have to create a new object.

18 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 18 The StringBuffer Class In many string processing applications, we would like to change the contents of a string. In other words, we want it to be mutable. Manipulating the content of a string, such as replacing a character, appending a string with another string, deleting a portion of a string, and so on, may be accomplished by using the StringBuffer class.

19 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 19 StringBuffer Example StringBuffer word = new StringBuffer("Java"); word.setCharAt(0, 'D'); word.setCharAt(1, 'i'); Changing a string Java to Diva word : StringBuffer Java Before word : StringBuffer Diva After

20 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 20 Sample Processing Replace all vowels in the sentence with ‘X’. char letter; String inSentence = JOptionPane.showInputDialog(null, "Sentence:"); StringBuffer tempStringBuffer = new StringBuffer(inSentence); int numberOfCharacters = tempStringBuffer.length(); for (int index = 0; index < numberOfCharacters; index++) { letter = tempStringBuffer.charAt(index); if (letter == 'a' || letter == 'A' || letter == 'e' || letter == 'E' || letter == 'i' || letter == 'I' || letter == 'o' || letter == 'O' || letter == 'u' || letter == 'U' ) { tempStringBuffer.setCharAt(index,'X'); } JOptionPane.showMessageDialog(null, tempStringBuffer );

21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 21 The append and insert Methods We use the append method to append a String or StringBuffer object to the end of a StringBuffer object. –The method can also take an argument of a primitive data type. –Any primitive data type argument is converted to a string before it is appended to a StringBuffer object. We can insert a string at a specified position by using the insert method. Look at the API for other useful methods like delete and replace.

22 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 22 The StringBuilder Class This class is new to Java 5.0 (SDK 1.5) The class is added to the newest version of Java to improve the performance of the StringBuffer class. StringBuffer and StringBuilder support exactly the same set of methods, so they are interchangeable. There are advanced cases where we must use StringBuffer, but all sample applications in the book, StringBuilder can be used. Since the performance is not our main concern and that the StringBuffer class is usable for all versions of Java, we will use StringBuffer only in this book.

23 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 23 String Tokenizer A StringTokenizer object can be used to break a string up into smaller substrings (tokens) By default, the tokenizer separates the string at white space The default StringTokenizer constructor takes the original string to be separated as a parameter StringTokenizer st = new StringTokenizer( text); An alternate constructor allows you to specify different separators (delimiters). StringTokenizer st = new StringTokenizer( text, delims); NOTE: This is NOT in your text.

24 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 24 StringTokenizer Methods The hasMoreTokens method returns true if there are more tokens in the string. Each call to the nextToken method returns the next token in the string. If you need to know how many tokens there are, you can call countTokens

25 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 25 StringTokenizer with Delimiter You can use characters other than (or in addition to) whitespace to separate a String into tokens. StringTokenizer st = new StringTokenizer( text, delims); –delims is a String containing all the characters you want to have treated as separators " \t\n" is the default delimiter string ", !.?;,- \n\t" would use punctuation as well as space to separate tokens By default, the delimiter characters are thrown away –They can be returned as separate tokens (one character per token) by using a different constructor StringTokenizer st = new StringTokenizer( text, delims, true);


Download ppt "©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 9 - 1 Chapter 9 Characters and Strings (sections 9.1-9.2,"

Similar presentations


Ads by Google