Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA 19383 CSC141 Computer Science I 5/27/20161.

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

©2004 Brooks/Cole Chapter 7 Strings and Characters.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Fundamental Programming Structures in Java: Strings.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-2: Strings reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Copyright 2006 by Pearson Education 1 Building Java Programs Chapters 3-4: Using Objects.
Basic I/O - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 110/1/2015.
1 Text Processing. 2 Type char char : A primitive type representing single characters. –A String is stored internally as an array of char String s = "Ali.
Objects and Classes; Strings. 2 Classes and objects class: A program entity that represents either 1.A program / module, or 2.A type of objects* –A class.
1 Text processing. 2 text processing: Examining, editing, formatting text.  Text processing often involves for loops that examine the characters of a.
From C++ to Java A whirlwind tour of Java for C++ programmers.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Decision Making - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus 10/27/20151.
Types CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University (Chapter 4, Horstmann text)
SE-1010 Dr. Mark L. Hornick 1 Variables & Datatypes.
Introduction to Programming
String and Scanner CS 21a: Introduction to Computing I First Semester,
1 Fencepost loops suggested reading: The fencepost problem Problem: Write a static method named printNumbers that prints each number from 1 to a.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
1 BUILDING JAVA PROGRAMS CHAPTER 3 THE STRING CLASS.
String Processing Word processing term papers, writing memoirs, sending messages, responding to surveys, placing online orders and registering products.
1 Text processing Readings: Characters char : A primitive type representing single characters. Individual characters inside a String are stored.
Strings Mr. Smith AP Computer Science A. What are Strings? Name some of the characteristics of strings: A string is a sequence of characters, such as.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-3: Arrays for Tallying; Text Processing reading: 7.1, 4.4 self-checks: #1-9.
Department of Computer Engineering Using Objects Computer Programming for International Engineers.
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 CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
Topic 23 arrays - part 3 (tallying, text processing) Copyright Pearson Education, 2010 Based on slides bu Marty Stepp and Stuart Reges from
CHAPTER 6 GC Strings. THE CLASS STRING  Contains operations to manipulate strings.  String:  Sequence of zero or more characters.  Enclosed.
Data Types References:  Data Type:  In computer science and computer programming, a data type or simply type is a.
Copyright 2010 by Pearson Education Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, 4.3.
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 4 Lecture 4-3: Strings, char reading: 3.3, self-check: Ch. 4 #12, 15 exercises:
Building Java Programs
Building Java Programs
Building Java Programs Chapter 4
Chapter 2 Basic Computation
Lecture 8: The String class
Building Java Programs
Building Java Programs
Building Java Programs
Chapter 6 GC 101 Strings.
String class.
Conditional Execution
Building Java Programs Chapter 4.3
Conditional Execution
Strings string: An object storing a sequence of text characters.
Primitive Types Vs. Reference Types, Strings, Enumerations
Topic 13 procedural design and Strings
Building Java Programs
مساق: خوارزميات ومبادئ البرمجة الفصل الدراسي الثاني 2016/2015
Exposure Java 2015 Pre-AP®CS Edition Chapter 12 Slides String Methods
Topic 23 arrays - part 3 (tallying, text processing)
Building Java Programs
Lecture 8: The String Class and Boolean Zen
Building Java Programs
Building Java Programs
Building Java Programs
Using Objects (continued)
Building Java Programs
Building Java Programs
Building Java Programs
Strings string: An object storing a sequence of text characters.
Building Java Programs
Building Java Programs
Building Java Programs Chapter 4
More on iterations using
Presentation transcript:

Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 5/27/20161

2 text processing: often involves for loops that examine the characters of a string one by one. Two data types involved charString Represents individual charactersRepresents sequences of characters Primitive typeObject type (i.e., not primitive) Written with single quotesWritten with double quotes e.g.: ‘T’ ‘t’ ‘3’ ‘%’ ‘\n’ e.g.: “We the people” “1. Twas brillig, and the slithy toves\n” “” “T” Text Processing 5/27/2016

3 char : A primitive type representing single characters. P52. Individual characters inside a String are stored as char values. Literal char values are surrounded with apostrophe (single-quote) marks, such as 'a' or '4' or '\n' or '\'' Example, p67. char letter = 'S'; System.out.println(letter); // prints S System.out.println((int)letter); // prints 83, // explained on p956 Char Type 5/27/2016

Most programming languages use the ASCII character set. Java uses the Unicode character set which includes the ASCII character set. The Unicode character set includes characters from many different alphabets (but you probably won't use them). 5/27/20164

String : an object type for representing sequences of characters Sequence can be of length 0, 1, or longer Each element of the sequence is a char We write strings surrounded in double-quotes We can declare, initialize, assign, and use String variables in expressions just like other data types String s = “Hello, world\n”;// declare, init System.out.println(s);// use value s = s + “I am your master\n”; // concatenate // and assign String Type 5/27/20165

6 Unlike primitive types, object types can have methods. Here is a list of methods for strings: returns the index where the start of the given string appears in this string (-1 if not found)‏ indexOf( str )‏ returns a new string with all uppercase letters toUpperCase()‏ returns a new string with all lowercase letters toLowerCase()‏ returns the characters in this string from index1 up to, but not including, index2 substring( index1, index2 )‏ returns the number of characters in this string length()‏ returns the character at the given index charAt( index )‏ DescriptionMethod name String Methods 5/27/2016

7 The characters of a string can be accessed using the String object's charAt method. String indices start at 0. String word = “cola”; char firstLetter = word.charAt(0); if (firstLetter == 'c') { System.out.println("C is for cookie!"); } charAt(i):‘c’‘c’‘o’‘o’‘l’‘l’‘a’‘a’ Index i:0123 Starts at 0! 5/27/2016

Let s be a variable of type String General syntax for calling a String method: s. ( ) Some examples: String s = “Cola”; int len = s.length();// len == 4 char firstLetter = s.charAt(0); // ‘C’ int index = s.indexOf(“ol”); // index == 1 String sub = s.substring(1,3); // “ol” String up = s.toUpperCase(); // “COLA” String down = s.toLowerCase(); // “cola” 5/27/20168

9 char values can be concatenated with strings. char initial = 'P'; System.out.println(initial + ". Diddy"); You can compare char values with relational operators. 'a' < 'b' and 'Q' != 'q' Caution: You should NOT use these operators on a String ! Example: // print the alphabet for (char c = 'a'; c <= 'z'; c++) { //ASCII System.out.print(c); } Fun to play 5/27/2016

10 'h' is a char char c = 'h'; char values are primitive; you cannot call methods on them can't say c.length() or c.toUpperCase()‏ "h" is a String String s = "h"; Strings are objects; they contain methods that can be called can say s.length()1 can say s.toUpperCase()"H" can say s.charAt(0)'h' 5/27/2016

345 is an int int i = 345; int values are primitive; you cannot call methods on them CAN perform arithmetic: i = i * 2; // i==690 CANNOT say i.length() or i.charAt(0)‏ “345" is a String String s = “345"; Strings are objects; they contain methods that can be called can say s.length()// returns 3 can say s.charAt(1)// returns ‘4’ CANNOT perform arithmetic: s = s * 2; // ERROR! 5/27/201611

12 Objects (such as String ) should be compared for equality by calling a method named equals. Example: Scanner console = new Scanner(System.in); System.out.print("What is your name? "); String name = console.next(); if (name.equals("Barney")) { System.out.println("I love you, you love me,"); System.out.println("We're a happy family!"); } 5/27/2016

13 There are more methods of a String object that can be used in conditions. whether this string’s beginning matches the argument startsWith(str)‏ whether this string’s end matches the argument endsWith(str)‏ whether this string contains the same characters as the other, ignoring upper- vs. lowercase differences equalsIgnoreCase(str)‏ whether this string contains exactly the same characters as the other string equals(str)‏ DescriptionMethod 5/27/2016

14 Hypothetical examples, assuming the existence of various String variables: if (title.endsWith("M.D.")) { System.out.println("What's your number?"); } if (fullName.startsWith("Giorgio")) { System.out.println("When are you retiring?"); } if (lastName.equalsIgnoreCase("lumBerg")) { System.out.println("I need your TPS reports!"); } if (name.toLowerCase().indexOf("sr.") >= 0) { System.out.println("You must be old!"); } 5/27/2016

String Type Cast The ( String ) typecasts don’t work with primitive types, like char, int, and double. (String) ‘A’== TypeCastException (String) 27== TypeCastException However, there are easy ways to convert to and from strings: Converting to strings: int x to String : x + “” or “” + x double x to String : x + “” or “” + x char, boolean, or float x to String : same thing 5/27/201615

Converting from strings: String s to int : Integer.parseInt(s) String s to double : Double.parseDouble(s) … String s to char : Character.parseChar(s) 5/27/201616

17 char grade;.... // compute the grade if(grade=='A' || grade=='a') { System.out.println(“Great job!”); } else if(grade=='B' || grade=='b') { System.out.println(“Very nice job.”); } else if(grade=='C' || grade=='c') { System.out.println(“Good job.”); } else if(grade=='D' || grade=='d') { System.out.println(“Keep at it.”); } else { System.out.println(“Work harder!”); } if/else Variation Tedious! 5/27/2016

18 char grade;.... // compute the grade switch(grade) { case 'A','a': System.out.println(“Great job”); break; case 'B','b': System.out.println(“Very nice job”); break; case 'C','c': System.out.println(“Good job”); break; case 'D','d': System.out.println(“Keep at it”); break; default: System.out.println(“Work harder!”); } 5/27/2016

Exercises Write a program to handle a String s and an integer max that are inputted via keyboard. The result will be printed out, which contains the content of s abbreviated to at most max characters, but where the last three characters are ellipses (i.e., the characters …). If s is shorter than max characters, print out the original string. If max is less than 3, print out an empty string. 5/27/ Input: Hello how are you 10 Result output: The result is: Hello h... Input: Hello 10 Result output: The result is: Hello

Test1.pdf Test1.pdf 5/27/201620

Write a program to handle a secret message doc. The result will be printed out, which contains the second character of each word in doc, or a space if the word is only one letter long. 5/27/ public static void main(String [] args){ String [] doc = {"He sat us by a spinning drum.", "You obstinate old eel. Emma!"}; System.out.println("The result is: "+result); } Result output: The result is: easy problem

Test2.pdf Test2.pdf 5/27/201622