Lecture 4 CS2012.

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 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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings and Text.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 8 Strings and Text.
1 Chapter 3 Strings and Text I/O. 2 Objectives F To use the String class to process fixed strings. F To use the Character class to process a single character.
Fundamental Programming Structures in Java: Strings.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 7 Objects and Classes.
28-Jun-15 String and StringBuilder Part I: String.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Strings and Text I/O.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 10 Thinking in Objects.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
Chapter 7 Input/ and Exception Handling. The String Class A string is a sequence of characters. In many languages, strings are treated as an array of.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text.
String & Composition. Agenda This keyword. String class. String operations. Composition.
Chapter 7 Strings  Use the String class to process fixed strings.  Use the StringBuffer class to process flexible strings.  Use the StringTokenizer.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 8 Strings and Text.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 8 Strings 1.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) public static void main(String[]
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.
Programming Fundamentals I (COSC- 1336), Lecture 6 (prepared after Chapter 9 of Liang’s 2011 textbook) Stefan Andrei 11/24/20151 COSC-1336, Lecture 6.
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.
1 The String Class F Constructing a String: F Obtaining String length and Retrieving Individual Characters in a string F String Concatenation (concat)
CHAPTER 8 File Input Output Part 1: String. The String Class  Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome.
1 Chapter 9 Strings and Text I/O. 2 Objectives F To use the String class to process fixed strings. F To use the Character class to process a single character.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Strings.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 10 Thinking in Objects.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Fall 2013 Chapter 9 Strings.
CS 112 Programming 2 Lecture 04 Thinking in Objects (1)
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 10 Thinking in Objects.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 7 Strings Chapter.
Chapter 4 Mathematical Functions, Characters, and Strings 1.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
Strings Chapter 7 CSCI CSCI 1302 – Strings2 Outline Introduction The String class –Constructing a String –Immutable and Canonical Strings –String.
John Hurley Cal State LA
Chapter 9 Strings and Text I/O
String and StringBuffer classes
Chapter 4 Mathematical Functions, Characters, and Strings
Strings, Characters and Regular Expressions
Strings.
Lecture 5: Some more Java!
String and StringBuilder
Chapter 8 Strings and Text I/O
Unit-2 Objects and Classes
Chapter 9 Strings and Text I/O
String and StringBuilder
Chapter 9 Strings and Text I/O
String and StringBuilder
Chapter 9 Strings.
Lecture 07 String Jaeki Song.
String and StringBuilder
Chapter 10 Thinking in Objects
String methods 26-Apr-19.
Chapter 9 Strings and Text I/O
Chapter 10 Thinking in Objects Part 2
Chapter 7 Strings Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. Use the String class to process fixed.
Presentation transcript:

Lecture 4 CS2012

Strings A String consists of zero or more characters String is a class that contains many methods Strings are more complicated than they sound!

Constructing Strings String newString = new String(stringLiteral);   String message = new String("Welcome to Java"); Since strings are used frequently, Java provides a shorthand initializer for creating a string: String message = "Welcome to Java"; 3

Variables vs Objects Consider this code: int myInt = 1; 1 is a value myInt is a variable String s1 = "The moon is made of green cheese." "The moon is made of green cheese" is a String, an object of class String. s1 is a variable 4

Null A null value is one that does not exist. Variables whose data type is a class, like String, may exist without having any value: String s = null; A variable whose type is a primitive data type will be null if no value is set, but can't be set to null int x; // ok int x = null; //syntax error 5

Strings Are Immutable A String object is immutable; its contents cannot be changed. The following code does not change the contents of the String, it makes the variable s point to a different String in memory. String s = "Java"; s = "HTML"; 6

Interned Strings Since strings are immutable, if two different variables need to point to identical Strings, there is no need to save two separate Strings in memory. The JVM usually uses a unique instance for each set of string literals with the same character sequence. In other words, the following code sets up one String in memory, but two variables that point to it: String s1 = "John"; String s2 = "John"; Such an instance is said to be interned. If you set up a new String using the full new String syntax, however, the JVM will not use an interned String even if there is one with identical text. This code sets up two separate Strings with identical characters: String s1 = "John"' String s2 = new String("John"); 7

String Comparisons .equals(String otherString) test whether the text of this String is the same as the text of the other String 8

Examples s1 == s2 is false, because the == operation for Strings tests whether two Strings are the same object in memory, and we did not use the interned String s1 == s3 is true because without the new String() syntax, we used the interned String. Thus, s1 and s3 point to the same object in memory. 9

String Comparisons equals String s1 = new String("Welcome“); String s2 = "welcome"; if (s1.equals(s2)){ // s1 and s2 have the same contents } if (s1 == s2) { // s1 and s2 have the same memory reference 10

String Comparisons, cont. compareTo(Object object) String s1 = new String("Welcome"); String s2 = "welcome"; if (s1.compareTo(s2) > 0) { // s1 is greater than s2 } else if (s1.compareTo(s2) == 0) { // s1 and s2 have the same contents else // s1 is less than s2 11

public class StringDemo{ public static void main(String[] args){ String s1 = new String("Welcome"); String s2 = "welcome"; String s3 = s1; String s4 = new String("Welcome"); if (s1.equals(s2)){ System.out.println("s1 equals s2"); } else System.out.println("s1 does not equal s2"); if (s1 == s2) { System.out.println("s1 == s2"); else System.out.println("s1 != s2"); if (s1.equals(s3)){ System.out.println("s1 equals s3"); if (s1 == s3) { System.out.println("s1 == s3"); else System.out.println("s1 != s3"); if (s1.equals(s4)){ System.out.println("s1 equals s4"); else System.out.println("s1 does not equal s4"); if (s1 == s4){ System.out.println("s1 == s4"); else System.out.println("s1 != s4"); if (s1.compareTo(s2) < 0) { System.out.println("s1 < s2");

Escape Sequences Some characters will cause confusion in output What will happen if we try to execute this: System.out.println(""Hi,Mom""); Others, like backspace and tab, can’t be unambiguously typed Use escape characters for these cases 13

Escape Sequences Description Escape Sequence Backspace \b Tab \t Linefeed \n Carriage return \r (think of a typewriter) Backslash \\ Single Quote \' Double Quote \" 14

Escape Sequences } public class EscapeDemo{ public static void main(String[] args) { System.out.println("A\tB\rB\tC D\nDD\b E\\F \'Hi, Mom\' \"Hi, Mom\""); System.out.println("She said \"They tried to make me go to rehab, but I said \"No, No, No!\"\""); } 15

String Concatenation Appending a String or character to the end of another String is called concatenation. Three strings concatenated: String message = "Welcome " + "to " + "Java";   String s1 concatenated with character B: String s1 = "Supplement" + 'B'; // s1 becomes SupplementB To concatenate to existing String, create a new String and use concat(): String myString = "Good"; String myOtherString = myString.concat(" Morning"); 16

String Concatenation String s3 = s1.concat(s2); String s3 = s1 + s2; s1 + s2 + s3 + s4 + s5 same as (((s1.concat(s2)).concat(s3)).concat(s4)).concat(s5); 17

String Length, Characters, and Combining Strings 18

Finding String Length message = "Welcome"; Finding string length using the length() method: message = "Welcome"; message.length() (returns 7) 19

Retrieving Individual Characters in a String Do not use message[0] Use message.charAt(index) Index starts from 0 20

Strings public static void main(String[] args){ String s1 = new String("Welcome"); String s2 = " Shriners"; String s3 = s1.concat(s2); System.out.println(s3); String s4 = s1 + s2; System.out.println(s4); s1 = s1 + s2; System.out.println(s1); if(s1.startsWith("Wel")) System.out.println("\"" + s1 + "\"" + " starts with \"Wel!\""); System.out.println("Length of \"" + s1 + "\" is " + s1.length()); System.out.println("In the string \"" + s1 + "\", the character at position 4 is " + s1.charAt(4)); }

Extracting Substrings 22

Extracting Substrings You can extract a single character from a string using the charAt method. You can also extract a substring from a string using the substring method in the String class. String s1 = "Welcome to Java"; String s2 = s1.substring(0, 11) + "HTML"; 23

Converting, Replacing, and Splitting Strings 24

Examples "Welcome".toLowerCase() returns a new string, welcome. "Welcome".toUpperCase() returns a new string, WELCOME. " Welcome ".trim() returns a new string, Welcome. "Welcome".replace('e', 'A') returns a new string, WAlcomA. "Welcome".replaceFirst("e", "AB") returns a new string, WABlcome. "Welcome".replace("e", "AB") returns a new string, WABlcomAB. "Welcome".replace("el", "AB") returns a new string, WABlcome. 25

Finding a Character or a Substring in a String 26

Finding a Character or a Substring in a String "Welcome to Java".indexOf('W') returns 0. "Welcome to Java".indexOf('x') returns -1. "Welcome to Java".indexOf('o', 5) returns 9. "Welcome to Java".indexOf("come") returns 3. "Welcome to Java".indexOf("Java", 5) returns 11. "Welcome to Java".indexOf("java", 5) returns -1. "Welcome to Java".lastIndexOf('a') returns 14. 27

public static void main(String[] args){ String theString = "The baby fell out of the window\nI thought that her head would be split\nBut good luck was with " +" us that morning\nFor she fell in a bucket of #$%*!\n\nHere we are in this fancy French restaurant\nI hate to be " +" raising a snit\nBut waiter, I ordered creamed vichysoisse\nand you brought me a bowl full of #$%*!\n\n"; System.out.println("\nOld:\n" + theString); String newString = theString.replace("#$%*!", "shaving cream\nBe nice and clean\nShave every day and you'll always look keen!\n"); System.out.println("New:\n" + newString); }

StringBuilder The StringBuilder class is a supplement to the String class. StringBuilder is more flexible than String. You can add, insert, or append new contents into a string buffer, whereas the value of a String object is fixed once the string is created. You will often have to parse the StringBuilder to a String when you are done constructing it. 29

StringBuilder Constructors 30

Modifying Strings in the Builder 31

The toString, capacity, length, setLength, and charAt Methods 32

Examples 33 public static void main(String[] args) { StringBuilder stringBuilder = new StringBuilder("Welcome to "); System.out.println(stringBuilder); stringBuilder.append("Java"); stringBuilder.insert(11, "HTML and "); stringBuilder.delete(8, 11); // changes the builder to Welcome HTML and Java. stringBuilder.deleteCharAt(8); // changes the builder to Welcome TML and Java. stringBuilder.reverse(); // changes the builder to avaJ dna LMT emocleW stringBuilder.reverse(); // undoes the reverse() stringBuilder.replace(11, 15, " to"); // changes the builder to Welcome TML to Java. stringBuilder.delete(7,11); // back to Welcome to Java stringBuilder.setCharAt(0, 'w'); // sets the builder to welcome to Java. } 33

StringBuilder public class StringBuilderDemo{ public static void main(String[] Args){ StringBuilder sb = new StringBuilder("Bakey"); System.out.println(sb); sb.insert(4, "ry"); sb.deleteCharAt(5); // this will not do what you expect! sb.append(" " + sb.reverse()); sb.delete(sb.indexOf(" "), sb.length()); StringBuilder sb2 = new StringBuilder(sb); sb2.reverse(); sb.append(sb2); sb.insert(5," "); sb.replace(0,0,"Y"); sb.deleteCharAt(1); sb.reverse(); }

Appendix H Regular Expressions A regular expression (abbreviated regex) is a string that describes a pattern for matching a set of strings. Regular expression is a powerful tool for string manipulations. You can use regular expressions for matching, replacing, and splitting strings. 35

Matching, Replacing and Splitting by Patterns You can match, replace, or split a string by specifying a Regex. This is an extremely useful and powerful feature. Regular expression usage is complex to beginning students. For this reason, two simple patterns are used in this section. Please refer to Supplement III.F, “Regular Expressions,” for further studies. "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*"); "Java is cool".matches("Java.*"); 36

Matching, Replacing and Splitting by Patterns The replaceAll, replaceFirst, and split methods can be used with a regular expression. For example, the following statement returns a new string that replaces $, +, or # in "a+b$#c" by the string NNN. String s = "a+b$#c".replaceAll("[$+#]", "NNN"); System.out.println(s); Here the regular expression [$+#] specifies a pattern that matches $, +, or #. So, the output is aNNNbNNNNNNc. 37

Matching, Replacing and Splitting by Patterns The following statement splits the string into an array of strings delimited by some punctuation marks. String[] tokens = "Java,C?C#,C++".split("[.,:;?]"); for (int i = 0; i < tokens.length; i++) System.out.println(tokens[i]); 38

Matching Strings "Java".matches("Java"); "Java".equals("Java"); Appendix H Matching Strings "Java".matches("Java"); "Java".equals("Java"); "Java is fun".matches("Java.*") "Java is cool".matches("Java.*") "Java is powerful".matches("Java.*") 39

Regular Expression Syntax Appendix H Regular Expression Syntax 40

Examples String s = "Java Java Java".replaceAll("v\\w", "wi") ; Appendix H Examples String s = "Java Java Java".replaceAll("v\\w", "wi") ; String s = "Java Java Java".replaceFirst("v\\w", "wi") ; String[] s = "Java1HTML2Perl".split("\\d"); 41