Week 4 - Lecture 2 - Chapter 9

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 28

1

CHAPTER 9 STRINGS

9.2 The String Class


9.2.1 Constructing a String
9.2.3 String Comparisons
9.2.4 String Length, Characters, and Combining Strings
9.2.5 Obtaining Substrings
9.2.6 Converting, Replacing, and Splitting Strings
9.2.1 CONSTRUCTING A STRING
2

• A string is a sequence of characters.

• Constructing a String:

To create a string use the syntax:


String s = new String(stringLiteral);

Example:
String s = new String("Welcome to Java");
Java treats a string literal as a String object. Thus, the
following statement is also valid:
String s = "Welcome to Java";
STRINGS ARE IMMUTABLE
3

A String object is immutable; its contents cannot be changed.


Does the following code change the contents of the string?
String s = "Java";
s = "HTML";
animation
TRACE CODE
4

String s = "Java";
s = "HTML";

After executing String s = "Java"; After executing s = "HTML";

s : String s : String This string object is


now unreferenced
String object for "Java" String object for "Java"

Contents cannot be changed : String

String object for "HTML"


animation
TRACE CODE
5

String s = "Java";
s = "HTML";

After executing String s = "Java"; After executing s = "HTML";

s : String s : String This string object is


now unreferenced
String object for "Java" String object for "Java"

Contents cannot be changed : String

String object for "HTML"


9.2.3 STRING COMPARISONS
6

java.lang.String
+equals(s1: String): boolean Returns true if this string is equal to string s1.
+equalsIgnoreCase(s1: String): Returns true if this string is equal to string s1 case-
boolean insensitive.
+compareTo(s1: String): int Returns an integer greater than 0, equal to 0, or less than 0
to indicate whether this string is greater than, equal to, or
less than s1.
+compareToIgnoreCase(s1: String): Same as compareTo except that the comparison is case-
int insensitive.
+regionMatches(index: int, s1: String, Returns true if the specified subregion of this string exactly
s1index: int, len: int): boolean matches the specified subregion in string s1.
+startsWith(prefix: String): boolean Returns true if this string starts with the specified prefix.
+endsWith(suffix: String): boolean Returns true if this string ends with the specified suffix.
STRING COMPARISONS (CONTINUED)
7

• equals() is used to compare the contents of strings

String s1 = new String("Welcome");


String s2 = "Welcome";
String s3 = "Hi";

if (s1.equals(s2))
// checks if s1 and s2 have the same contents
// For the above example it gives true
if (s1.equals(s3))
// checks if s1 and s3 have the same contents
// For the above example it gives false
STRING COMPARISONS (CONTINUED)
8

• == is used to compare the string references

String s1 = new String("Welcome");


String s2 = "Welcome";
String s3 = s1;

if (s1 == s2)
// checks if s1 and s2 have the same reference
// For the above example it gives false
if (s1 == s3) {
// checks if s1 and s3 have the same reference
// For the above example it gives true
STRING COMPARISONS (CONTINUED)
9

• equalsIgnoreCase()
Ignores the letter case (lower versus upper case) when comparing

String s1 = new String("Welcome");


String s2 = "welcome";

if (s1.equals(s2))
// gives false since w is different from W
if (s1.equalsIgnoreCase(s2))
// gives true since w and W are considered the same
STRING COMPARISONS (CONTINUED)
10

• compareTo()

s1.compareTo(s2)
This method returns 0 if s1 is equal to s2, a value less than 0 if s1 is
lexicographically (i.e., in terms of Unicode ordering) less than s2,
and a value greater than 0 if s1 is lexicographically greater than s2.
String s1 = new String("Welcome");
String s2 = "Welcome";
if (s1.compareTo(s2) > 0) // is s1 greater than s2?

if (s1.compareTo(s2) < 0) // is s1 smaller than s2?

if (s1.compareTo(s2) == 0) // do s1 and s2 have the same contents?


STRING COMPARISONS (CONTINUED)
11

• compareTo()

String s1 = "abc", s2 = "abc";


String s3 = "aba", s4 = "abd";
int x;
x = s1.compareTo(s2);
// x = 0 since s1 and s2 are equal

x = s1.compareTo(s3);
// x > 0 since s1 > s3 because ‘c’ is > ‘a’ (‘c’ = 99 & ‘a’ = 97)
// See ASCII Table

x = s1.compareTo(s4);
// x < 0 since s1 < s4 because ‘c’ is < ‘d’ (‘c’ = 99 & ‘d’ = 100)
STRING COMPARISONS (CONTINUED)
12

• compareToIgnoreCase()

String s1 = "abc", s2 = "ABC";


int x;

x = s1.compareTo(s2);
// x > 0 since s1 > s2 because ‘a’ > ‘A’ (‘a’ = 97, ‘A’ = 65)

x = s1.compareToIgnoreCase(s2);
// x = 0 since s1 and s2 are equal when the case is ignored
STRING COMPARISONS (CONTINUED)
13

• regionMatches()

This method compares portions of two strings for equality.


regionMatches(index: int, s1: String, s1Index: int, len: int): boolean

String s1 = "scde", s2 = "abcdef";

if (s1.regionMatches(1,s2,2,3))
// 1 is the starting index in s1, and 2 is the starting index in s2, 3
is the length or the number of characters to be compared.
STRING COMPARISONS (CONTINUED)
14

• startsWith(prefix) to check whether string starts with a


specified prefix.
• endsWith(suffix) to check whether string ends with a specified
suffix.

String s = "howtodoinjava.com";

if(s.startsWith("how")) // gives true


if(s.startsWith("howl")) // gives false

if(s.endsWith("com")) // gives true


if(s.endsWith("dom")) // gives false
9.2.4 STRING LENGTH, CHARACTERS,
AND
15 COMBINING STRINGS

java.lang.String
+length(): int Returns the number of characters in this string.
+charAt(index: int): char Returns the character at the specified index from this string.
+concat(s1: String): String Returns a new string that concatenate this string with string s1.
string.
FINDING STRING LENGTH
16

Finding string length using the length() method:

String s = "Welcome";
int len = s.length(); // len = 7
RETRIEVING A CHAR IN A STRING
17

String message = "Welcome to Java";


We cannot use message[index]

Instead we use message.charAt(index)

Index starts from 0

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

message.charAt(0) message.length() is 15 message.charAt(14)


RETRIEVING A CHAR IN A STRING
18

String message = "Welcome";


for (int i = 0; i < message.length(); i++)
System.out.println(message.charAt(i));

Output
W
e
l
c
o
m
e
STRING CONCATENATION
19

String s1 = "Welcome", s2 = " to Java";


String s3 = s1.concat(s2);
S3 will contain the string “Welcome to Java”.
The conact method does the same job as the string
concatenation operator (+).
String s3 = s1 + s2;

The difference is that the + can applied between a string


value and a value from another type such as int or char. The
method concat( ) works only with the String type.
9.2.5 OBTAINING SUBSTRINGS
20

java.lang.String
+substring(beginIndex: int): Returns this string’s substring that begins with the character at the
String specified beginIndex and extends to the end of the string.

+substring(beginIndex: int, Returns this string’s substring that begins at the specified
endIndex: int): String beginIndex and extends to the character at index endIndex – 1.
Note that the character at endIndex is not part of the substring.

You can extract a single character from a string using the charAt
method. You can also extract a substring from a string using the
substring method in the String class.
OBTAINING SUBSTRINGS (CONTINUED)
21

String s1 = "Welcome to Java";


To extract the substring from index 11 till the end we write:
String s2 = s1.substring(11);
Now S2 will contain the string “Java”.

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

message.substring(0, 11) message.substring(11)


OBTAINING SUBSTRINGS (CONTINUED)
22

String s1 = "Welcome to Java";


To extract the substring from index 0 till index 10 we write:
String s2 = s1.substring(0,11);
Now S2 will contain the string “Welcome to ” including a space at the
end. Note that the character at index 11 is not part of the substring.

Indices 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14

message W e l c o m e t o J a v a

message.substring(0, 11) message.substring(11)


9.2.6 CONVERTING, REPLACING,
23
AND SPLITTING STRINGS
java.lang.String
+toLowerCase(): String Returns a new string with all characters converted to lowercase.
+toUpperCase(): String Returns a new string with all characters converted to uppercase.
+trim(): String Returns a new string with blank characters trimmed on both sides.
+replace(oldChar: char, newChar: Returns a new string that replaces all matching character in this string
char): String with the new character.
+replaceFirst(oldString: String, Returns a new string that replaces the first matching substring in this
newString: String): String string with the new substring.
+replaceAll(oldString: String, Returns a new string that replace all matching substrings in this string
newString: String): String with the new substring.
+replace(oldString: String, Works exactly like replaceAll.
newString: String): String
Returns an array of strings consisting of the substrings split by the
+split(delimiter: String): String[] delimiter.
EXAMPLES
24
"Welcome".toLowerCase() returns a new string, welcome.

"Welcome".toUpperCase() returns a new string, WELCOME.

" Welcome to Java ".trim() returns a new string, Welcome to Java.

"Welcome".replace('e', 'A') returns a new string, WAlcomA.

"Welcome".replaceFirst("e", "AB") returns a new string, WABlcome.

"Welcome".replaceAll("e", "AB") returns a new string, WABlcomAB.

"Welcome".replace("e", "AB") returns a new string, WABlcomAB.


SPLITTING A STRING – EXAMPLE 1
25

The split method can be used to extract tokens from a string with the specified delimiters.
For example, in the following code the delimiter is the string “#”.

String s = "Java#HTML#Perl";
String[] tokens = s.split("#");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
The delimiter # is not stored in the array tokens (an array of
strings).
0 Java
The output will be:
tokens 1 HTML Java HTML Perl
2 Perl
SPLITTING A STRING – EXAMPLE 2
26

The delimiter can be composed of more than one character since it is a string. For example,
in the following code the delimiter is “ab”.

String s = "cdabefabgh";
String[] tokens = s.split("ab");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i]+ " ");

0 cd The output will be:


1 ef cd ef gh
tokens
2 gh
SPLITTING A STRING – EXAMPLE 3
27

The delimiter can be a space.

String s = "Welcome to Java";


String[] tokens = s.split(" ");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);

The output will be:


Welcome
0 Welcome to
Java
tokens 1 to
2 Java
THE “.” DELIMITER
28

If want to split a string using the delimiter dot “.” such as


String a = "a.jpg";
String [ ] str = a.split(".");

The split does not work because "." is a reserved character.


Instead, we should use the following statement:
String [ ] str = a.split("\\.");

0 a
str
1 jpg

You might also like