Strings Chapter 6.

Slides:



Advertisements
Similar presentations
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 9 Strings.
Advertisements

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 Working with String Duo Wei CS110A_ Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
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.
Chapter 9 Characters and Strings. Topics Character primitives Character Wrapper class More String Methods String Comparison String Buffer String Tokenizer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
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,
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.
28-Jun-15 String and StringBuilder Part I: String.
The String Class. Objectives: Learn about literal strings Learn about String constructors Learn about commonly used methods Understand immutability of.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 9 Characters and Strings (sections ,
1 Strings and String Operations  What is a Strings?  Internal Representation of Strings  Getting Substrings from a String  Concatenating Strings 
Lesson 3 – Regular Expressions Sandeepa Harshanganie Kannangara MBCS | B.Sc. (special) in MIT.
Class T{ public static int id; public static int num = 5; public int n; public boolean c; public static void setNumberOfBicycles(int val) { num=val; //
Java Methods A & AB Chapter 10 - Strings. Ch 10 Goals Understand Strings indepth Learn strategies to deal with the immutability of Strings Learn how to.
String Class in Java java.lang Class String java.lang.Object java.lang.String java.lang.Object We do not have to import the String class since it comes.
String Class. Objectives and Goals Identify 2 types of Strings: Literal & Symbolic. Learn about String constructors and commonly used methods Learn several.
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.
An Introduction to Java Programming and Object-Oriented Application Development Chapter 7 Characters, Strings, and Formatting.
Strings Carol Yarbrough AP Computer Science Instructor Alabama School of Fine Arts.
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.
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.
Jaeki Song JAVA Lecture 07 String. Jaeki Song JAVA Outline String class String comparisons String conversions StringBuffer class StringTokenizer class.
Strings JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Strings Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and.
String Definition A String is a set of characters that behaves as a single unit. The characters in a String include upper-case and lower-case letters,
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved Java’s String Class.
String String Builder. System.String string is the alias for System.String A string is an object of class string in the System namespace representing.
G51PR1 Introduction to Programming I University of Nottingham Unit 8 : Strings.
Strings And other things. Strings Overview The String Class and its methods The char data type and Character class StringBuilder, StringTokenizer classes.
Strings and ArrayLists April 23, 2012 ASFA AP CS.
String Definition A string is a set of characters that behaves as a single unit. The characters in a string include upper-case and lower- case letters,
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:
17-Feb-16 String and StringBuilder Part I: String.
"Chapter 9" Strings Java Methods Maria Litvin Gary Litvin
The Methods and What You Need to Know for the AP Exam
The String Class.
Strings, Characters and Regular Expressions
Strings, Characters and Regular Expressions
Strings, StringBuilder, and Character
EKT 472: Object Oriented Programming
String and String Buffers
String String Builder.
String Class.
Char data type and the String class.
Primitive Types Vs. Reference Types, Strings, Enumerations
Chapter 6 The while Statement
Modern Programming Tools And Techniques-I Lecture 11: String Handling
String and StringBuilder
Chapter 7: Strings and Characters
Object Oriented Programming
MSIS 655 Advanced Business Applications Programming
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.
String and StringBuilder
Java – String Handling.
Lecture 07 String Jaeki Song.
String and StringBuilder
CS2011 Introduction to Programming I Strings
String methods 26-Apr-19.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

Strings Chapter 6

Goals and Objectives Write code using the String class. Manipulate and compare strings using the String class and its methods. Learn about literal strings Learn about String constructors and commonly used methods Develop code with correct and efficient use of repetitive control structures. Apply problem solving strategies. Understand immutability of strings Learn to format numbers into strings and extract numbers from strings Learn several useful methods of the Character class Learn about the StringBuffer class

Part of the java.lang package The String Class 9/11/2018 8:36 AM Part of the java.lang package A String object is comprised of a sequence of characters with the first character at index position 0 Methods length() toString() charAt(int) replace(oldChar, newChar) substring(int) substring(int,int) toUpperCase() toLowerCase() concat(str) trim() indexOf(char) indexOf(char, int) indexOf(str); indexOf(str,int) lastIndexOf(char) lastIndexOf(char,int) lastIndexOf(str) lastIndexOf(str,int) equals(str) equalsIgnoreCase() compareTo(str) compareToIgnoreCase(str) Refer to page 138 in the text. The String class is used for representing text. The first character of a string is at index position 0. The last character is at position length()-1.

The String class An object of the String class represents a string of characters. Like other classes, String has constructors and methods. Unlike other classes, String has two operators, + and += (used for concatenation). There is no need to import java.lang.String because the java.lang package is imported automatically into all classes. Like the char type, String objects internally represent characters using Unicode. The + and += operators for strings are an exception in Java, the only example of operators that work with objects.

Literal Strings Literal strings are anonymous constant objects of the String class that are defined as text in double quotes. Literal strings don’t have to be constructed: they are “just there.” This is one of the reasons why String constructors are not used very often: instead of constructing a string you just write a literal string.

Literal Strings (cont’d) The string text may include “escape” characters (\) For example: \\ stands for \ \n stands for the newline character \t – tab \” – double quotes \’ – single quote \" stands for the double quote character. String s1 = "Biology”; String s2 = "C:\\jdk1.4\\docs"; String s3 = "Hello\n";

String Assignment heLlO hello 9/11/2018 8:36 AM String Assignment Strings are immutable. Assigning a new string to a String object simply changes the object reference to point to the new string in memory: String text; text = "heLlO"; text = text.toLowerCase(); text heLlO hello Note: This slide contains animations. Press the space bar or click the mouse button to display each animation. This slide contains three (3) animations. Refer to page 139 in the text. The object instantiation, String text, associates the object name text with a memory location <press space bar> The first assignment statement points to the location in memory that stores the mixed-case string <press space bar> The second assignment statement, moves the pointer to the location in memory that stores the lowercase string <press space bar>

Empty Strings An empty string has no characters; its length is 0. Not to be confused with an uninitialized string: String s1 = ""; String s2 = new String(); Empty strings You may need an empty string as a starting point when you plan to append items to a string. private String errorMsg; errorMsg is null

Null String String name; // null string Does not have a length.

Declaring a String String name = “Bob”; 0 1 2 OR 0 1 2 OR String name = new String(“Bob’); 0 1 2 B o b B o b

new Operator String s1 = “Bob”; String s2 = s1; String s2 = new String(“Bob”); S1 Bob S2 Bob s1 Bob s2

Constructors String’s no-args and copy constructors are not used much. Other constructors convert arrays into strings String s1 = new String (); String s2 = new String (s1); String s1 = ""; String s2 = s1; As explained earlier, it is a good idea to avoid the copy constructor. One useful constructor converts an array of chars into a String.

Immutability Once created, a string cannot be changed: none of its methods changes the string. Such objects are called immutable. Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change. If all the instance fields in a class are private and none of the methods can directly or indirectly set the field values, then the class’s objects are immutable. A few String methods create and return a different string, but none of them changes the string for which they were called. The Integer, Character, and Double classes, discussed later, are immutable, too.

Immutability (cont’d) Advantage: more efficient, no need to copy. String s1 = "Sun"; String s2 = s1; String s1 = "Sun"; String s2 = new String(s1); s1 s1 "Sun" It is safe for immutable objects to copy references rather than the contents. Cloning (creating copies of objects) is not required. This may save time when Strings are stored in lists, etc. "Sun" s2 s2 "Sun" Less efficient: wastes memory OK

Immutability (cont’d) Disadvantage: less efficient — you need to create a new string and throw away the old one for every small change. String s = "sun"; char ch = Character.toUpperCase(s.charAt (0)); s = ch + s.substring (1); The immutability of strings may also result in tremendous inefficiency when strings are modified often, especially when a string is gradually built by appending characters or numbers to it. Programmers should use the StringBuffer class for these tasks. s "sun" "Sun"

9/11/2018 8:36 AM Comparing Strings The String class includes several methods for comparing two strings: equals() equalsIgnoreCase() compareTo() compareToIgnoreCase() indexOf() lastIndexOf() Refer to page 140 in the text.

Methods — length, charAt int length (); char charAt (k); Returns the number of characters in the string Returns the k-th char Character positions in strings are numbered starting from 0 Character positions in strings are counted starting from 0, so str.charAt(0) returns the first character and str.charAt(str.length() - 1) returns the last character. This is consistent with indices in arrays (Chapter 12): the index of the first element is 0. Returns: ”Flower".length(); ”Wind".charAt (2); 6 ’n'

Methods — substring String s2 = s.substring (i, k); returns the substring of chars in positions from i to k-1 String s2 = s.substring (i); returns the substring from the i-th char to the end strawberry i k strawberry i substring is overloaded: there are two versions. It is actually convenient that the k-th char is excluded from the substring. The length of the substring is k ‑ i. str.substring (i) is the same as str.substring(i, str.length()). Returns: "raw" "happy" "" (empty string) ”strawberry".substring (2,5); "unhappy".substring (2); "emptiness".substring (9);

Methods — Concatenation String result = s1 + s2; concatenates s1 and s2 String result = s1.concat (s2); the same as s1 + s2 result += s3; concatenates s3 to result result += num; converts num to String and concatenates it to result It looks like the += operator for strings violates immutability. In fact the string is not changed, rather the reference is reassigned. s1 += s2 is the same as s1 = s1 + s2. So if you have String s = "Nice ", t = s; s += "day"; the value of t remains "Nice ", while s becomes "Nice day".

Methods — Find (indexOf) 0 8 11 15 String date ="July 5, 2012 1:28:19 PM"; date.indexOf ('J'); 0 date.indexOf ('2'); 8 date.indexOf ("2012"); 8 date.indexOf ('2', 9); 11 date.indexOf ("2020"); -1 date.lastIndexOf ('2'); 15 Returns: String has four overloaded versions of indexOf and four versions of lastIndexOf. lastIndexOf(ch, fromPos) starts looking at fromPos and goes backward towards the beginning of the string. (starts searching at position 9) (not found)

Methods — Comparisons returns true if the string s1 is equal to s2 boolean b = s1.equals(s2); returns true if the string s1 is equal to s2 boolean b = s1.equalsIgnoreCase(s2); returns true if the string s1 matches s2, case-blind int diff = s1.compareTo(s2); returns the “difference” s1 - s2 int diff = s1.compareToIgnoreCase(s2); returns the “difference” s1 - s2, case-blind You cannot use relational operators for comparing the contents of strings. s1.compareTo(s2) returns an int. Basically if s1 is “smaller” than s2, the result is negative, and if s1 is “larger” the result is positive. compareTo returns 0 whenever equals returns true. Here is how Java docs describe compareTo: Compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The character sequence represented by this String object is compared lexicographically to the character sequence represented by the argument string. The result is a negative integer if this String object lexicographically precedes the argument string. The result is a positive integer if this String object lexicographically follows the argument string. The result is zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return true. This is the definition of lexicographic ordering. If two strings are different, then either they have different characters at some index that is a valid index for both strings, or their lengths are different, or both. If they have different characters at one or more index positions, let k be the smallest such index; then the string whose character at position k has the smaller value, as determined by using the < operator, lexicographically precedes the other string. In this case, compareTo returns the difference of the two character values at position k in the two string — that is, the value: this.charAt(k)-anotherString.charAt(k) If there is no index position at which they differ, then the shorter string lexicographically precedes the longer string. In this case, compareTo returns the difference of the lengths of the strings — that is, the value: this.length()-anotherString.length()

Methods — Replacements String s2 = s1.trim (); returns a new string formed from s1 by removing white space at both ends String s2 = s1.replace(oldCh, newCh); returns a new string formed from s1 by replacing all occurrences of oldCh with newCh String s2 = s1.toUpperCase(); String s2 = s1.toLowerCase(); returns a new string formed from s1 by converting its characters to upper (lower) case Note that these methods do not change the string s1 but create and return a new string. trim() only removes whitespace at the ends of the string, not in the middle.

Replacements (cont’d) Example: how to convert s1 to upper case A common bug: s1 = s1.toUpperCase(); s1 remains unchanged s1.toUpperCase(); s1.toUpperCase(); doesn’t do anything. The correct statement is: s1 = s1.toUpperCase(); The variable s1 is changed to refer to the new string returned by s1.toUpperCase(); the old string is disposed of.

Numbers to Strings Three ways to convert a number into a string: 1. String s = "" + num; 2. String s = Integer.toString (i); String s = Double.toString (d); 3. String s = String.valueOf (num); Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods. You can also convert a char to a string by using String s = "" + ch; or String s = ch + ""; By convention, a static method valueOf in a class converts something (its arguments) into an object of this class. For example: public class Fraction { public static Fraction valueOf(double x) {...} should take a double and return a corresponding Fraction. Here String.valueOf(x) returns a string.

Numbers to Strings (cont’d) The DecimalFormat class can be used for formatting numbers into strings. import java.text.DecimalFormat; ... DecimalFormat money = new DecimalFormat("0.00"); double amt = 56.7381; String s = money.format (amt); As usual in Java, there is a hierarchy of formatting subclasses and rather elaborate rules for specifying different formats. For example, you can define DecimalFormat dollars = new DecimalFormat("$#,##0.00"); Then System.out.println ( dollars.format(12345678.987)); displays $12,345,678.99 56.7381 "56.74"

Numbers to Strings (cont’d) Java 5.0 added printf and format methods: int m = 5, d = 19, y = 2007; double amt = 123.5; System.out.printf ( "Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt); String s = String. format( "Date: %02d/%02d/%d Amount = %7.2f\n", m, d, y, amt); printf and format are methods with variable numbers of parameters. Besides %d and %f, the format string can have other specifiers for the output data elements. See Java API. Displays, sets s to: "Date: 05/19/2007 Amount 123.50"

Numbers from Strings String s1 = "-123", s2 = "123.45"; int n = Integer.parseInt(s1); double x = Double.parseDouble(s2); These methods throw a NumberFormatException if s does not represent a valid number (integer, real number, respectively). In a real program you should use exception handling with number conversions to avoid aborting the program when the user mistypes a character, as explained in the next slide.

Numbers from Strings (cont’d) A safer way: int n; do { try { n = Integer.parseInt(s); } catch (NumberFormatException ex) System.out.println("Invalid input, reenter"); } while (...); The try-catch statement is repeated until the user enters a valid string.

Character Methods java.lang.Character is a “wrapper” class that represents characters as objects. Character has several useful static methods that determine the type of a character (letter, digit, etc.). Character also has methods that convert a letter to the upper or lower case. Character is a wrapper class for char.

Character Methods (cont’d) if (Character.isDigit (ch)) ... .isLetter... .isLetterOrDigit... .isUpperCase... .isLowerCase... .isWhitespace... return true if ch belongs to the corresponding category Whitespace is space, tab, newline, etc. See Java docs for the formal definition of whitespace characters.

Character methods (cont’d) char ch2 = Character.toUpperCase (ch1); .toLowerCase (ch1); if ch1 is a letter, returns its upper (lower) case; otherwise returns ch1 int d = Character.digit (ch, radix); returns the int value of the digit ch in the given int radix char ch = Character.forDigit (d, radix); returns a char that represents int d in a given int radix For example Character.digit('7',10) returns 7 and Character.digit('A', 16) returns 10. Character.forDigit(7,10) returns '7'.

The StringBuffer Class Represents a string of characters as a mutable object Constructors: StringBuffer() // empty StringBuffer of the default capacity StringBuffer(n) // empty StringBuffer of a given capacity StringBuffer(str) // converts str into a StringBuffer Adds setCharAt, insert, append, and delete methods The toString method converts this StringBuffer into a String substring and indexOF(String) methods work the same way as in String.

Review: What makes the String class unusual? How can you include a double quote character into a literal string? Is "length".length() allowed syntax? If so, what is the returned value? Define immutable objects. Does immutability of Strings make Java more efficient or less efficient? What makes the String class unusual? + and += operators and literal strings How can you include a double quote character into a literal string? \" Is "length".length() allowed syntax? If so, what is the returned value? Yes, it is valid and returns 6. Define immutable objects. Objects that cannot be changed by calling their methods (nor by directly manipulating their fields). Does immutability of strings make Java more efficient or less efficient? It depends. It may be more efficient if the code involves making many copies of strings. It is less efficient if the code involves changing characters in strings or assembling strings from separate items (chars or numbers). Actually the latter situation is more common. You should then use the StringBuffer class rather than String.

Review (cont’d): How do you declare an empty string? Why are String constructors not used very often? If the value of String city is "Boston", what is returned by city.charAt (2)? By city.substring(2, 4)? How come String doesn’t have a setCharAt method? Is s1 += s2 the same as s1 = s1 + s2 for strings? How do you declare an empty string? String s = ""; Why are String constructors not used very often? Because you can simply assign a literal string to a variable, so there is no need to make copies of strings. If the value of String city is "Boston", what is returned by city.charAt(2)? By city.substring(2,4)? 's' and "st", respectively. How come String doesn’t have a setCharAt method? To keep it immutable. StringBuffer has setCharAt(ch,pos). Is s1 += s2 the same as s1 = s1 + s2 for strings? Yes.

Review (cont’d): What do the indexOf methods do? Name a few overloaded versions. What is more efficient for strings: == and other relational operators or equals and compareTo methods? What does the trim method do? What does s.toUpperCase() do to s? What does the toString method return for a String object? What do the indexOf methods do? Name a few overloaded versions. Find a character or a substring in a string. indexOf(char), indexOf(String), indexOf(char, int fromPos), indexOf(String, int fromPos) What is more efficient for strings: == and other relational operators or equals and compareTo methods? This is not a matter of efficiency: you must use equals and compareTo to compare the contents of strings; == compares references, which are equal only if they refer to exactly the same string. What does the trim method do? It returns a new string which contains this string with whitespace removed at the ends. What does s.toUpperCase() do to s? Nothing: s is immutable. What does the toString method return for a String object? This string.

Review (cont’d): Name a simple way to convert a number into a string. Which class has a method for converting a String into an int? Name a few Character methods that help identify the category to which a given character belongs. What is the difference between the String and StringBuffer classes? Name a simple way to convert a number into a string "" + num; Which class has a method for converting a String into an int? Integer (the method parseInt) Name a few Character methods that help identify the category to which a given char belongs. isDigit, isLetter, isUpperCase, isLowerCase, isWhitespace. What is the difference between the String and StringBuffer classes? StringBuffer objects are mutable; StringBuffer is more efficient for assembling a string from pieces. It has methods for inserting, appending, and deleting characters.