string - cis 1068 program design and abstraction

24
String - CIS 1068 Program Design and Abstraction Zhen Jiang CIS Dept. Temple University SERC 347, Main Campus Email: [email protected] 1 06/20/22

Upload: camille-vaughn

Post on 30-Dec-2015

43 views

Category:

Documents


1 download

DESCRIPTION

String - CIS 1068 Program Design and Abstraction. Zhen Jiang CIS Dept. Temple University 1008 Wachman Hall, Main Campus Email: [email protected]. Table of Contents. Introduction to text processing Char type String type String methods Fun to play String type cast If variation - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: String - CIS 1068  Program Design and Abstraction

String - CIS 1068 Program Design and Abstraction

Zhen Jiang

CIS Dept.

Temple University

SERC 347, Main Campus

Email: [email protected]/19/23

Page 2: String - CIS 1068  Program Design and Abstraction

Table of Contents

Introduction to text processing Char type String type String methods Fun to play String type cast If variation Summary

204/19/23

Page 3: String - CIS 1068  Program Design and Abstraction

3

text processing: often involves for loops that examine the characters of a string one by one.

Two data types involvedchar String

Represents individual characters

Represents sequences of characters

Primitive type Object type (i.e., not primitive)

Written with single quotes Written 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

04/19/23

Page 4: String - CIS 1068  Program Design and Abstraction

4

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 SSystem.out.println((int)letter); // prints 83,

// explained on p956

Char Type

04/19/23

Page 5: String - CIS 1068  Program Design and Abstraction

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

04/19/23 5

Page 6: String - CIS 1068  Program Design and Abstraction

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

04/19/23 6

Page 7: String - CIS 1068  Program Design and Abstraction

7

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 letterstoUpperCase()

returns a new string with all lowercase letterstoLowerCase()

returns the characters in this string from index1 up to, but not including, index2

substring(index1,index2)

returns the number of characters in this stringlength()

returns the character at the given indexcharAt(index)

DescriptionMethod name

String Methods

04/19/23

Page 8: String - CIS 1068  Program Design and Abstraction

8

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 ’ ‘o ’ ‘l ’ ‘a ’

Index i: 0 1 2 3

Starts at 0!

04/19/23

Page 9: String - CIS 1068  Program Design and Abstraction

Let s be a variable of type String General syntax for calling a String method:

s.<method>(<args>)

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”

04/19/23 9

Page 10: String - CIS 1068  Program Design and Abstraction

10

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 alphabetfor (char c = 'a'; c <= 'z'; c++) { //ASCII System.out.print(c);

}

Fun to play

04/19/23

Page 11: String - CIS 1068  Program Design and Abstraction

11

'h' is a charchar c = 'h';

char values are primitive; you cannot call methods on them

can't say c.length() or c.toUpperCase()

"h" is a StringString 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'04/19/23

Page 12: String - CIS 1068  Program Design and Abstraction

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!

04/19/23 12

Page 13: String - CIS 1068  Program Design and Abstraction

13

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

}

04/19/23

Page 14: String - CIS 1068  Program Design and Abstraction

14

There are more methods of a String object that can be used in <test> 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

04/19/23

Page 15: String - CIS 1068  Program Design and Abstraction

15

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

04/19/23

Page 16: String - CIS 1068  Program Design and Abstraction

String Type CastThe (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 “” + xdouble x to String: x + “” or “” + xchar, boolean, or float x to String: same thing

04/19/23 16

Page 17: String - CIS 1068  Program Design and Abstraction

Converting from strings:String s to int: Integer.parseInt(s)String s to double: Double.parseDouble(s) …

String s to char: Character.parseChar(s)

04/19/23 17

Page 18: String - CIS 1068  Program Design and Abstraction

18

char grade;.... // compute the gradeif(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!

04/19/23

Page 19: String - CIS 1068  Program Design and Abstraction

19

char grade;.... // compute the gradeswitch(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!”);}

04/19/23

Page 20: String - CIS 1068  Program Design and Abstraction

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.

04/19/23 20

Input: Hello how are you10

Result output: The result is: Hello

h...

Input: Hello10

Result output: The result is: Hello

Page 21: String - CIS 1068  Program Design and Abstraction

www.cis.temple.edu/~jiang/1068StringTest1.pdf

04/19/23 21

Page 22: String - CIS 1068  Program Design and Abstraction

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.

04/19/23 22

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

Page 23: String - CIS 1068  Program Design and Abstraction

www.cis.temple.edu/~jiang/1068StringTest2.pdf

04/19/23 23

Page 24: String - CIS 1068  Program Design and Abstraction

Char type, p52 Variable, declaration, and value, p67 String, p81 String methods, p83-86 String/char values, and concatenation, p81-83 String type cast, p83 String use in input and output, p91-95

Summary of Concepts

2404/19/23