©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,

Slides:



Advertisements
Similar presentations
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 9 Characters and Strings.
Advertisements

1 StringBuffer & StringTokenizer Classes Chapter 5 - Other String Classes.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
1 Strings and Text I/O. 2 Motivations Often you encounter the problems that involve string processing and file input and output. Suppose you need to write.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Java Programming Strings Chapter 7.
Chapter 10 Review. Write a method that returns true is s1 and s2 end with the same character; otherwise return false. Sample Answer: public boolean lastChar(String.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 9: Characters * Character primitives * Character Wrapper class.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
23-Jun-15 Strings, Etc. Part I: String s. 2 About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects,
Intro to OOP with Java, C. Thomas Wu Characters and Strings
Fundamental Programming Structures in Java: Strings.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Odds and Ends Strings (from Chapter 9) StringTokenizer.
© 2000 McGraw-Hill Introduction to Object-Oriented Programming with Java--WuChapter Chapter 8 Characters and Strings.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
Characters and Strings. Representation of single characters Data type char is the data type that represents single characters, such as letters, numerals,
Characters, String and Regular expressions. Characters char data type is used to represent a single character. Characters are stored in a computer memory.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 9 Characters and Strings.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis Chapter.
Chapter 9: Text Processing and More about Wrapper Classes Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Characters In Java, single characters are represented.
Characters In Java single characters are represented using the data type char. Character constants are written as symbols enclosed in single quotes, for.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (adapted from.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
String Manipulation Chapter 15 This chapter explains the String facilities. You have already seen some of the main methods of the String class.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Portions adapted with permission from the textbook author. CS-1020 Dr. Mark L. Hornick 1 Regular Expressions and String processing Animated Version.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 String Comparisons Compare string contents with the equals(String s) method not == String s0 = “ Java”;
Chapter 7: Characters, Strings, and the StringBuilder.
CHAPTER 9 Text Processing and More about Wrapper Classes Copyright © 2016 Pearson Education, Inc., Hoboken NJ.
1 Textual Data Many computer applications manipulate textual data word processors web browsers online dictionaries.
10-2 Chapter 10 discusses the following main topics:  Introduction to Wrapper Classes  Character Testing and Conversion with the Character Class  More.
String Handling StringBuffer class character class StringTokenizer class.
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Strings and Text File I/O (and Exception Handling) Corresponds with Chapters 8 and 17.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 10: Text Processing and More about Wrapper Classes Starting.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Strings and Related Classes String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer.
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. For example,
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
Chapter 3 : Basic Concept Of Java
Strings.
Primitive Types Vs. Reference Types, Strings, Enumerations
String and StringBuilder
Chapter 7: Strings and Characters
MSIS 655 Advanced Business Applications Programming
Advanced String handling
Chapter 8 Characters In Java single characters are represented using the data type char. Character constants are written as symbols enclosed in single.
String and StringBuilder
Strings A string is a sequence of characters that is treated as a single value. Strings are objects. We have been using strings all along. Every time.
Lecture 07 String Jaeki Song.
String and StringBuilder
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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);

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter String Tokenizer 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

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

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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';

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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’

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Static CharacterMethods boolean methods isDigit( char) isLetter( char) isWhitespace( char) isUpperCase( char) isLowerCase(char) other methods char toLowerCase( char) char toUpperCase( char) Look at the API to see if you can find any others you might have a use for

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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)

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter The String Class is Immutable In Java a String object is immutable –This means once a String object is created, it cannot be changed, such as replacing a character with another character or removing a character –The String methods we have used so far do not change the original string. They created a new string from the original. For example, substring creates a new string from a given string. The String class is defined in this manner for efficiency reasons.

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

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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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 );

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter 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.