Lecture String
Lecture String
1
Copyright 2008 by Pearson Education
Objects and classes
Non-primitive data type @ reference type
object: An entity that contains:
data (variables), and
behavior (methods).
Examples:
The class String represents objects that store text.
The class DrawingPanel represents graphical window objects.
The class Scanner represents objects that read information
from the keyboard, files, and other sources.
2
Copyright 2008 by Pearson Education
Strings
string: An object storing a sequence of text characters.
Unlike most other objects, a String is not created with new.
Examples:
3
Copyright 2008 by Pearson Education
Indexes
Characters of a string are numbered with 0-based indexes:
index 0 1 2 3 4 5 6 7
char P . D i d d y
4
Copyright 2008 by Pearson Education
String methods
Method name Description
indexOf(str) index where the start of the given string
appears in this string (-1 if it is not there)
length() number of characters in this string
substring(index1, the characters in this string from index1
index2) (inclusive) to index2 (exclusive);
or if index2 omitted, grabs till end of string
substring(index1)
toLowerCase() a new string with all lowercase letters
toUpperCase() a new string with all uppercase letters
These methods are called using the dot notation:
String gangsta = "Dr. Dre";
System.out.println(gangsta.length()); // 7
5
Copyright 2008 by Pearson Education
String method examples
// index 012345678901
String s1 = "Stuart Reges";
String s2 = "Marty Stepp";
System.out.println(s1.length()); // 12
System.out.println(s1.indexOf("e")); // 8
System.out.println(s1.substring(7, 10)) // "Reg"
String s3 = s2.substring(2, 8);
System.out.println(s3.toLowerCase()); // "rty st"
6
Copyright 2008 by Pearson Education
Modifying strings
Methods like substring, toLowerCase, etc. create/return
a new string, rather than modifying the current string.
String s = "lil bow wow";
s.toUpperCase();
System.out.println(s); // lil bow wow
7
Copyright 2008 by Pearson Education
Strings as parameters
public class StringParameters {
public static void main(String[] args) {
sayHello("Marty");
8
Copyright 2008 by Pearson Education
Strings as user input
Scanner's next method reads a word of input as a String.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
name = name.toUpperCase();
System.out.println(name + " has " + name.length() +
" letters and starts with " + name.substring(0, 1));
Output:
What is your name? Madonna
MADONNA has 7 letters and starts with M
9
Copyright 2008 by Pearson Education
Comparing strings
Relational operators such as < and == fail on objects.
Scanner console = new Scanner(System.in);
System.out.print("What is your name? ");
String name = console.next();
if (name == "Barney") {
System.out.println("I love you, you love me,");
System.out.println("We're a happy family!");
}
This code will compile, but it will not print the song.
10
Copyright 2008 by Pearson Education
The equals method
Objects are compared using a method named equals.
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!");
}
11
Copyright 2008 by Pearson Education
String test methods
Method Description
equals(str) whether two strings contain the same characters
equalsIgnoreCase(str) whether two strings contain the same characters,
ignoring upper vs. lower case
startsWith(str) whether one contains other's characters at start
endsWith(str) whether one contains other's characters at end
contains(str) whether the given string is found within this one
13
Copyright 2008 by Pearson Education
Strings answer
// This program prints your "gangsta" name.
import java.util.*;
public class GangstaName {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type your name, playa: ");
String name = console.nextLine();
System.out.print("(M)ale or (F)emale: ");
String gender = console.next();
// split name into first/last name and initials
String first = name.substring(0, name.indexOf(" "));
String last = name.substring(name.indexOf(" ") + 1);
last = last.toUpperCase();
String fInitial = first.substring(0, 1);
String title;
if (gender.equalsIgnoreCase("m")) {
title = "Daddy";
} else {
title = "Goddess";
}
System.out.println("Your gangsta name is \"" + fInitial + ". "
+ last + " " + title + " " + first + "-izzle\"");
}
} 14
Copyright 2008 by Pearson Education
Java String split() method
The java string split() method splits this string against
given regular expression and returns a char array.
15
Copyright 2008 by Pearson Education
Type char
char : A primitive type representing single characters.
Each character inside a String is stored as a char value.
Literal char values are surrounded with apostrophe
(single-quote) marks, such as 'a' or '4' or '\n' or '\''
16
Copyright 2008 by Pearson Education
The charAt method
The chars in a String can be accessed using the charAt
method.
String food = "cookie";
char firstLetter = food.charAt(0); // 'c'
System.out.println(firstLetter + " is for " + food);
System.out.println("That's good enough for me!");
Examples:
'A' is 65, 'B' is 66, ' ' is 32
'a' is 97, 'b' is 98, '*' is 42
18
Copyright 2008 by Pearson Education
char vs. String
"h" is a String
'h' is a char (the two behave differently)
What is s + 1 ? What is c + 1 ?
What is s + s ? What is c + c ?
19
Copyright 2008 by Pearson Education
Comparing char values
You can compare char values with relational operators:
'a' < 'b' and 'X' == 'X' and 'Q' != 'q'
20
Copyright 2008 by Pearson Education
Java Regular Expressions
A regular expression is a sequence of characters that forms
a search pattern.
When you search for data in a text, you can use this search
pattern to describe what you are searching for.
Java does not have a built-in Regular Expression class, but
we can import the java.util.regex package to work with
regular expressions.
•Pattern Class - Defines a pattern (to be used in a search)
•Matcher Class - Used to search for the pattern
•PatternSyntaxException Class - Indicates syntax error in
a regular expression pattern
https://www.w3schools.com/java/java_regex.asp
21
Copyright 2008 by Pearson Education
22
Copyright 2008 by Pearson Education