John Hurley Cal State LA

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.
Strings An extension of types A class that encompasses a character array and provides many useful behaviors Chapter 9 Strings are IMMUTABLE.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text I/O.
©2004 Brooks/Cole Chapter 7 Strings and Characters.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Strings and Text.
Programming 2 CS112- Lab 2 Java
String class  Construct a string  String str = new String(“welcome”);  Char[] charr = {‘G’, ‘o’, ‘o’, ‘d’};  String mes = new String(charr);  A full.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 9 Strings and Text.
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Strings and Text I/O.
The string data type String. String (in general) A string is a sequence of characters enclosed between the double quotes "..." Example: Each character.
John Hurley Spring 2011 Cal State LA CS 201 Lecture 6:
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, 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.
John Hurley Cal State LA CS 201 Lecture 5. 2 Loops A loop performs a set of instructions repeatedly as long as some condition is met while (x != 0) {
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”;
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)
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 8 File Input Output Part 1: String. The String Class  Constructing a String: String message = "Welcome to Java“; String message = new String("Welcome.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
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.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
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,
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1 Chapter 10 Thinking in Objects.
ITK 168 – More Variables 10/13/05. Another example of using instance variables and constants  Go through SimpleBot  Modify SimpleBot to “teleport”
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.
Lecture 5: java.lang.Math, java.lang.String and Characters Michael Hsu CSULA.
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.
Chapter 9 Strings and Text I/O
String and StringBuffer classes
Chapter 4 Mathematical Functions, Characters, and Strings
Strings.
Lecture 5: Some more Java!
String Handling in JAVA
String and StringBuilder
Chapter 8 Strings and Text I/O
Unit-2 Objects and Classes
String and StringBuilder
Chapter 9 Strings and Text I/O
Chapter 9 Strings.
Lecture 07 String Jaeki Song.
String and StringBuilder
Chapter 10 Thinking in Objects
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.
Lecture 4 CS2012.
Presentation transcript:

John Hurley Cal State LA CS 201 Lecture 6: John Hurley Cal State LA

Character Codes Computers store information in bits, not as characters Numeric values are easy to map to bits; just convert them to base 2 and then map each digit to a bit There are several code systems to assign numeric values to characters

Character Codes ASCII developed in the early 1960s, when memory was much more expensive than it is now. Originally used to send teletype data over phone lines, which are noisy 128 (27) possible characters The first 33 are control characters, originally used to control teletypes

Character Codes Unicode Used in Java Superset of ASCII 65536 values The first 128 are the same as ASCII Adds other alphabets, mathematical symbols,etc.

Unicode and Hardware

Character Codes public class ASCIIUnicodeDemo{ public static void main(String[] args){ for(int charNum = 0; charNum < 128; charNum++){ System.out.println("Character " + charNum + " is " + (char) charNum); } Why do we get a blank line after 10 and before 11?

Character Codes chars can be compared using <, =, > operators Apply the math operators to the Unicode values It’s probably obvious that ‘a’ < ‘b’ Not obvious that ‘A’ < ‘a’ ‘0’ < ‘a’ ‘/’ < ‘a’ 8 < ‘5’ !!

Character Codes public class UnicodeCompare{ public static void main(String[] args){ for(int charNum = 0; charNum < 128; charNum++){ char currChar = (char) charNum; System.out.println("'" + currChar + "': " + " less than 'A'? " + (currChar < 'A')); } System.out.println("And by the way, it is " + (8 < '5') + " that 8 < '5'");

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";

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

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

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";

animation Trace Code String s = "Java"; s = "HTML";

animation Trace Code String s = "Java"; s = "HTML";

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");

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.

animation Trace Code

Trace Code

Trace Code

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

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

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

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

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

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!\"\""); }

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");

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);

String Length, Characters, and Combining Strings

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

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

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

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";

Converting, Replacing, and Splitting Strings

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.

Finding a Character or a Substring in a String

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.

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); }

public static void main(String[] args){ String theString = "'Take some more tea,' the March Hare said to Alice, very earnestly.\n'I've had nothing yet,' Alice replied in " + "an offended tone, 'so I can't take more.'\n'You mean you can't take LESS,' said the Hatter: 'it's very easy to take MORE " + "than nothing. \n'Nobody asked YOUR opinion,' said Alice."; System.out.println("\n" + theString); System.out.println("\n\nall lower case: " + theString.toLowerCase() + "\n"); System.out.println("\n\nsubstring from index 3 to end: " + theString.substring(3) + "\n"); System.out.println("\n\nsubstring starting at index 24, ending at 30: " +theString.substring (24, 30) + "\n"); System.out.println("character at index 39 is: " + theString.charAt(39) + "\n"); System.out.println("\n\nfirst y is at: " + theString.indexOf('y')); System.out.println("\n\nsubstring from first y to just before last y: " + theString.substring(theString.indexOf('y'), theString.lastIndexOf('y'))); }

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.

StringBuilder Constructors

Modifying Strings in the Builder

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

Examples 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. }

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(); }