string - cis 1068 program design and abstraction
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 PresentationTRANSCRIPT
String - CIS 1068 Program Design and Abstraction
Zhen Jiang
CIS Dept.
Temple University
SERC 347, Main Campus
Email: [email protected]/19/23
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
www.cis.temple.edu/~jiang/1068StringTest1.pdf
04/19/23 21
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
www.cis.temple.edu/~jiang/1068StringTest2.pdf
04/19/23 23
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