Programming Lecture 9 Strings and Characters Chapter 8

  • Slides: 33
Download presentation
Programming – Lecture 9 Strings and Characters (Chapter 8) • Enumeration • ASCII /

Programming – Lecture 9 Strings and Characters (Chapter 8) • Enumeration • ASCII / Unicode, special characters • Character class • Character arithmetic • Strings vs. characters • String methods • Top-Down design • String. Tokenizer 1

Five-Minute Review 1. What do &, |, !, ^ mean for integers? 2. What

Five-Minute Review 1. What do &, |, !, ^ mean for integers? 2. What is a generic class? What are Array. Lists, when should they be used? 3. Which three areas do we distinguish in memory? What is stored where? What is garbage collection? 4. What is recursion? 5. What is a linked list? 2

Enumerated Types in Java Strategy 1: Named constants public static final int NORTH =

Enumerated Types in Java Strategy 1: Named constants public static final int NORTH = 0; public static final int EAST = 1; public static final int SOUTH = 2; public static final int WEST = 3; int dir = NORTH; if (dir == EAST). . . switch (dir) { case SOUTH: . . . Strategy 2: enum public enum Direction { NORTH, EAST, SOUTH, WEST } Direction dir = Direction. NORTH; if (dir == Direction. EAST). . . switch (dir) { case SOUTH: . . .

ASCII Subset of Unicode 00 x 01 x 02 x 03 x 04 x

ASCII Subset of Unicode 00 x 01 x 02 x 03 x 04 x 05 x 06 x 07 x 10 x 11 x 12 x 13 x 14 x 15 x 16 x 17 x 0 00 b 20 30 space ( 0 8 @ H P X ` h p x 1 01 t 21 31 ! ) 1 9 A I Q Y a i q y 2 02 n 22 32 " * 2 : B J R Z b j r z 3 03 11 13 23 33 # + 3 ; C K S [ c k s { 4 04 f 24 34 $ , 4 < D L T d l t | 5 05 r 25 35 % 5 = E M U ] e m u } 6 06 16 26 36 &. 6 > F N V ^ f n v ~ 7 07 17 27 37 ' / 7 ? G O W _ g o w 177

Special Characters that are not printing characters Escape sequence: backslash + character/digits b Backspace

Special Characters that are not printing characters Escape sequence: backslash + character/digits b Backspace f Form feed (starts a new page) n Newline (moves to the next line) r Return (moves to beginning of line without advancing) t Tab (moves horizontally to the next tab stop) \ The backslash character itself ' The character ' (required only in character constants) " The character " (required only in string constants) ddd The character whose Unicode value is octal number ddd

Methods in Character Class static boolean is. Digit(char ch) Determines if the specified character

Methods in Character Class static boolean is. Digit(char ch) Determines if the specified character is a digit. static boolean is. Letter(char ch) Determines if the specified character is a letter. static boolean is. Letter. Or. Digit(char ch) Determines if the specified character is a letter or a digit. static boolean is. Lower. Case(char ch) Determines if the specified character is a lowercase letter. static boolean is. Upper. Case(char ch) Determines if the specified character is an uppercase letter. static boolean is. Whitespace(char ch) Determines if the specified character is whitespace (spaces and tabs). static char to. Lower. Case(char ch) Converts ch to its lowercase equivalent, if any. If not, ch is returned unchanged. static char to. Upper. Case(char ch) Converts ch to its uppercase equivalent, if any. If not, ch is returned unchanged.

Character Arithmetic char letter. A = 'a'; char letter. B = letter. A++; letter.

Character Arithmetic char letter. A = 'a'; char letter. B = letter. A++; letter. B letter. A == == == 'B' 'b' 'a' 'b' 'B' False True False public char random. Letter() { return (char) rgen. next. Int('A', 'Z'); } public boolean is. Digit(char ch) { return (ch >= '0' && ch <= '9'); }

Exercise: Character Arithmetic public char to. Hex. Digit(int if (n >= 0 && n

Exercise: Character Arithmetic public char to. Hex. Digit(int if (n >= 0 && n <= 9) { return (char) ('0' + } else if (n >= 10 && n return (char) ('A' + } else { return '? '; } } n) { n); <= 15) { n - 10);

Strings vs. Characters ch = Character. to. Upper. Case(ch); str = str. to. Upper.

Strings vs. Characters ch = Character. to. Upper. Case(ch); str = str. to. Upper. Case(); Q: Why not simply: str. to. Upper. Case(); A: Because Strings are immutable!

Selecting Characters from a String str = "hello, world"; h e l l o

Selecting Characters from a String str = "hello, world"; h e l l o , 0 1 2 3 4 5 6 w o r l d 7 8 9 10 11 int twelve = str. length(); char h = str. char. At(0);

Concatenation println("hi". concat(" there")); println("hi" + " there"); println(0 + 1); println(0 + "1");

Concatenation println("hi". concat(" there")); println("hi" + " there"); println(0 + 1); println(0 + "1"); println(false + true); println("" + false + true); println(false + true + ""); println(false + "" + true); hi there 1 01 Error! falsetrue

Aside: Expression Evaluation Different operators ordered by Precendence: * has higher precedence than +;

Aside: Expression Evaluation Different operators ordered by Precendence: * has higher precedence than +; overridden by paren's 2 + 3 * 4 != (2 + 3) * 4 First evaluate *, then +; 3 is bound to *, not to + Same operators ordered by Associativity: + is left-associative; overridden by paren's false + true + "" != false + (true + "") 1 + 1 E 100 + -1 E 100 != 1 + (1 E 100 + -1 E 100) First evaluate left + (operator), then evaluate right + Operands of operator ordered by evaluation direction: Java evaluates left-to-right (undefined in C or C++!) With i initially 0: i + 2 * ++i == 2 First evaluate left operand, then evaluate right operand

Operator Description Level Associativity []. () ++ -- access array element access object member

Operator Description Level Associativity []. () ++ -- access array element access object member invoke a method post-increment post-decrement 1 left to right ++ -+ ! ~ pre-increment pre-decrement unary plus unary minus logical NOT bitwise NOT 2 right to left () new cast object creation 3 right to left * / % multiplicative 4 left to right -+ + additive string concatenation 5 left to right [http: //introcs. princeton. edu/java/11 precedence/]

Operator Description Level Associativity << >> <<< shift 6 left to right =< <

Operator Description Level Associativity << >> <<< shift 6 left to right =< < => > instanceof relational type comparison 7 left to right == =! equality 8 left to right & bitwise AND 9 left to right ^ bitwise XOR 10 left to right | bitwise OR 11 left to right && conditional AND 12 left to right || conditional OR 13 left to right : ? conditional 14 right to left =/ =* =- =+ = =| =^ =& =% =<<< =>> assignment 15 right to left [http: //introcs. princeton. edu/java/11 precedence/]

Extracting Substrings string. substring(index-first, index-after-last); String prog = "infprogoo". substring(3, 7);

Extracting Substrings string. substring(index-first, index-after-last); String prog = "infprogoo". substring(3, 7);

Checking for Equality String s 1 = new String("hello"); String s 2 = new

Checking for Equality String s 1 = new String("hello"); String s 2 = new String("hello"); s 1 == s 2 s 1. equals(s 2) False True String s 3 = "hello"; String s 4 = "hello"; String s 5 = "hel" + "lo"; (s 3 == s 4) && (s 4 == s 5) s 1. intern() == s 2. intern() JVM uses string literal pool True

Comparing Characters and Strings char c 1 = 'a', c 2 = 'c'; c

Comparing Characters and Strings char c 1 = 'a', c 2 = 'c'; c 1 < c 2 True String s 1 = "a", s 2 = "c"; s 1. compare. To(s 2) -2

Searching in a String str = "informatik"; str. index. Of('i') str. index. Of("n") str.

Searching in a String str = "informatik"; str. index. Of('i') str. index. Of("n") str. index. Of("form") str. index. Of('x') 0 1 2 -1 str. index. Of('i', 1) 8

Other Methods in String Class int last. Index. Of(char ch) or last. Index. Of(String

Other Methods in String Class int last. Index. Of(char ch) or last. Index. Of(String str) Returns the index of the last match of the argument, or -1 if none exists. boolean equals. Ignore. Case(String str) Returns true if this string and str are the same, ignoring differences in case. boolean starts. With(String str) Returns true if this string starts with str. boolean ends. With(String str) Returns true if this string ends with str. String replace(char c 1, char c 2) Returns a copy of this string with all instances of c 1 replaced by c 2. String trim() Returns a copy of this string with leading and trailing whitespace removed. String to. Lower. Case() Returns a copy of this string with all uppercase characters changed to lowercase. String to. Upper. Case() Returns a copy of this string with all lowercase characters changed to uppercase

Simple String Idioms Iterating through characters in a string: for (int i = 0;

Simple String Idioms Iterating through characters in a string: for (int i = 0; i < str. length(); i++) { char ch = str. char. At(i); . . . code to process each character in turn. . . } Growing new string character by character: String result = ""; for (whatever limits are appropriate to application) {. . . code to determine next character to be added. . . result += ch; }

Exercises: String Processing public String to. Upper. Case(String str) { String result = "";

Exercises: String Processing public String to. Upper. Case(String str) { String result = ""; for (int i = 0; i < str. length(); i++) { char ch = str. char. At(i); result += Character. to. Upper. Case(ch); } return result; } public int index. Of(char ch) { for (int i = 0; i < length(); i++) { if (ch == char. At(i)) return i; } return -1; }

reverse. String public void run() { println("This program reverses a string. "); private String

reverse. String public void run() { println("This program reverses a string. "); private String reverse. String(String str) { String str = read. Line("Enter a string: "); String result = ""; String rev = reverse. String(str); for ( int i = 0; i < str. length(); i++ ) { println(str + " spelled backwards is " + rev); result = str. char. At(i) + result; } } rev return result; DESSERTS } result str STRESSED str DESSERTS ERTS TS S STRESSED i 023456781 Reverse. String This program reverses a string. Enter a string: STRESSED spelled backwards is DESSERTS skip simulation

Pig Latin 1. If word begins with consonant, move initial consonant string to end

Pig Latin 1. If word begins with consonant, move initial consonant string to end add suffix ay: scram amscray 2. If word begins with vowel, add suffix way: appleway

Top-Down Design public void run() { Tell the user what the program does. Ask

Top-Down Design public void run() { Tell the user what the program does. Ask the user for a line of text. Translate the line into Pig Latin and print it on the console. } public void run() { print("This program translates "); println("a line into Pig Latin. "); String line = read. Line("Enter a line: "); println(translate. Line(line)); }

String. Tokenizer public String. Tokenizer( String str, String delim, boolean return. Delims) // Optional

String. Tokenizer public String. Tokenizer( String str, String delim, boolean return. Delims) // Optional String. Tokenizer tokenizer = new String. Tokenizer("ene moo"); while (tokenizer. has. More. Tokens()) { String token = tokenizer. next. Token(); code to process the token }

private String translate. Line(String line) { String result = ""; String. Tokenizer tokenizer =

private String translate. Line(String line) { String result = ""; String. Tokenizer tokenizer = new String. Tokenizer(line, DELIMITERS, true); while (tokenizer. has. More. Tokens()) { String token = tokenizer. next. Token(); if (is. Word(token)) { token = translate. Word(token); } result += token; } return result; } private static final String DELIMITERS = "!@#$%^&*()_-+={[}]: ; "'<, >. ? /~`|\ ";

private boolean is. Word(String token) { for (int i = 0; i < token.

private boolean is. Word(String token) { for (int i = 0; i < token. length(); i++) { char ch = token. char. At(i); if (!Character. is. Letter(ch)) return false; } return true; }

private String translate. Word(String word) { int vp = find. First. Vowel(word); if (vp

private String translate. Word(String word) { int vp = find. First. Vowel(word); if (vp == -1) { return word; } else if (vp == 0) { return word + "way"; } else { String head = word. substring(0, vp); String tail = word. substring(vp); return tail + head + "ay"; } }

Pig. Latin public void run() { println("This program translates a line into Pig Latin.

Pig. Latin public void run() { println("This program translates a line into Pig Latin. "); private line) { String line =translate. Line(String read. Line("Enter a line: "); String result = ""; println( translate. Line(line) ); private String translate. Word(String word) { String. Tokenizer tokenizer = } int vp = find. First. Vowel(word); new String. Tokenizer(line, DELIMITERS, true); line if ( vp == -1 ) { while ( tokenizer. has. More. Tokens() ) { return word; String token = tokenizer. next. Token(); this is pig latin. } else if ( vp == 0 ) { if ( is. Word(token) ) token = translate. Word(token); return word + "way"; result += token; } else { } tokenizer String head = word. substring(0, vp); return result; String tail = word. substring(vp); this is pig latin. } return tail + head + "ay"; token result line } isthay latin igpay isway this pig is. isthay isway isthay isway igpay atinlay this } atinlay vp head tailis pig latin. word 2 0 1 th p l is ig atin this pig is latin Pig. Latin This program translates a line into Pig Latin. Enter a line: this is pig latin. isthay isway igpay atinlay. skip simulation

Summary I • Principle of enumeration: map non-numeric properties/data (e. g. characters) to numbers

Summary I • Principle of enumeration: map non-numeric properties/data (e. g. characters) to numbers • Java provides enum types • char/Character maps characters to Unicode • Distinguish printing characters and special characters • Express special characters with escape sequences 49

Summary II • Conceptually, strings are ordered collections of characters • Strings are immutable

Summary II • Conceptually, strings are ordered collections of characters • Strings are immutable • Strings should be compared with equals or compare. To, not with == • Expression evaluation is governed by precedence, associativity and (in Java) leftto-right evaluation 50

Final Exam: March 15, 13: 45

Final Exam: March 15, 13: 45

https: //www. youtube. com/ watch? v=Hsx 5 R 94 YFAA

https: //www. youtube. com/ watch? v=Hsx 5 R 94 YFAA