0% found this document useful (0 votes)
129 views29 pages

Object-Oriented Problem Solving: Strings

This document provides an overview of string handling in Java, including: - The String class represents character sequences and is immutable. Strings can be constructed from string literals or character arrays. - Methods like length(), charAt(), concat(), and equals() allow manipulating and comparing string values. Regular expressions provide powerful pattern matching for strings. - The StringBuilder and StringBuffer classes allow mutating string values and are useful for operations like concatenation that produce new string objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
129 views29 pages

Object-Oriented Problem Solving: Strings

This document provides an overview of string handling in Java, including: - The String class represents character sequences and is immutable. Strings can be constructed from string literals or character arrays. - Methods like length(), charAt(), concat(), and equals() allow manipulating and comparing string values. Regular expressions provide powerful pattern matching for strings. - The StringBuilder and StringBuffer classes allow mutating string values and are useful for operations like concatenation that produce new string objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Object-Oriented Problem Solving

Strings
Based on Chapters 4 & 10 of “Introduction to
Java Programming” by Y. Daniel Liang.

Eng. Asma Abdel Karim


Computer Engineering Department
Outline
• The String Class (4.4)(10.10)
• The StringBuilder and StringBuffer Classes
(10.11)

Eng. Asma Abdel Karim 2


Computer Engineering Department
The String Class
• A string is a sequence of characters.
• String is a predefined class in the Java library,
just like the classes System and Scanner.
• The String class has 13 constructors and more
than 40 methods for manipulating strings.
• A string literal is a sequence of characters
enclosed inside double quotes.
– Example: “Welcome to Java!”

Eng. Asma Abdel Karim 3


Computer Engineering Department
Constructing a String
• You can create a string object from a string literal or
from an array of characters.
• The String type is not a primitive type. It is a reference
type.
• In the example below, message is a reference variable
that references a string object with contents Welcome
to Java.
• Examples:
– String message = new String (“Welcome to Java!”);
– String message = “Welcome to Java!”;
– char[] charArray = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y'};
– String message = new String(charArray); Java treats a string literal
as a String object.
Eng. Asma Abdel Karim 4
Computer Engineering Department
Immutable Strings
• A String object is immutable: its contents cannot be
changed.
• Example:
String s = “Java”;
s = “HTML”;

Eng. Asma Abdel Karim 5


Computer Engineering Department
Interned Strings
• The JVM uses a unique instance for string
literals with the same character sequence.
– In order to achieve efficiency and save memory.
– Such an instance is called an interned string.

Eng. Asma Abdel Karim 6


Computer Engineering Department
Interned Strings: Example

Output:
s1==s2 is false
s1==s3 is true

Eng. Asma Abdel Karim 7


Computer Engineering Department
Simple Methods for String Class

Eng. Asma Abdel Karim 8


Computer Engineering Department
Getting String Length
• You can use the length() method to return the number
of characters in a string. For example, the following
code
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "+
message.length());
• For convenience, Java allows you to use the string
literal to refer directly to strings without creating new
variables.
– Thus, "Welcome to Java".length() is correct and returns 15.
– Note that "" denotes an empty string and "".length() is 0.

Eng. Asma Abdel Karim 9


Computer Engineering Department
Getting Characters from a String
• The s.charAt(index) method can be used to retrieve a
specific character in a string s, where the index is between
0 and s.length()–1.
• Attempting to access characters in a string s out of bounds
is a common programming error. To avoid it, make sure that
you do not use an index beyond s.length() – 1.
• For example, s.charAt(s.length()) would cause a
StringIndexOutOfBoundsException.

Eng. Asma Abdel Karim 10


Computer Engineering Department
Concatenating Strings
• You can use the concat method to concatenate two strings.
• The statement shown below, for example, concatenates
strings s1 and s2 into s3:
String s3 = s1.concat(s2);
• Because string concatenation is heavily used in
programming, Java provides a convenient way to
accomplish it.
– You can use the plus (+) operator to concatenate two strings, so
the previous statement is equivalent to
String s3 = s1 + s2;
• The following code combines the strings message, " and ",
and "HTML" into one string:
String myString = message + " and " + "HTML";

Eng. Asma Abdel Karim 11


Computer Engineering Department
Converting Strings
• The toLowerCase() method returns a new string with
all lowercase letters and the toUpperCase() method
returns a new string with all uppercase letters.
– For example:
"Welcome".toLowerCase() returns a new string welcome.
"Welcome".toUpperCase() returns a new string WELCOME.
• The trim() method returns a new string by eliminating
whitespace characters from both ends of the string.
– The characters ' ', \t, \f, \r, or \n are known as whitespace
characters.
– For example,
"\t Good Night \n".trim() returns a new string Good Night.

Eng. Asma Abdel Karim 12


Computer Engineering Department
Comparing Strings

Eng. Asma Abdel Karim 13


Computer Engineering Department
Comparing Strings (Cont.)
• How do you compare the contents of two strings?
• You might attempt to use the == operator.
• However, the == operator checks only whether two strings
refer to the same object; it does not tell you whether they
have the same contents.
• Therefore, you cannot use the == operator to find out
whether two string variables have the same contents.
• Instead, you should use the equals method. The following
code, for instance, can be used to compare two strings:
if (string1.equals(string2))
System.out.println("string1 and string2 have the same contents");
else
System.out.println("string1 and string2 are not equal");

Eng. Asma Abdel Karim 14


Computer Engineering Department
Comparing Strings (Cont.)

Eng. Asma Abdel Karim 15


Computer Engineering Department
Comparing Strings (Cont.)
• The compareTo method can also be used to compare two strings.
• For example, consider the following code:
s1.compareTo(s2)
• The method returns:
– the value 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.
• The actual value returned from the compareTo method depends on
the offset of the first two distinct characters in s1 and s2 from left
to right.
• For example, suppose s1 is abc and s2 is abg, and s1.compareTo(s2)
returns -4.
– The first two characters (a vs. a) from s1 and s2 are compared.
Because they are equal, the second two characters (b vs. b) are
compared. Because they are also equal, the third two characters (c vs.
g) are compared. Since the character c is 4 less than g, the comparison
returns -4.
Eng. Asma Abdel Karim 16
Computer Engineering Department
Comparing Strings (Cont.)
• The String class also provides the equalsIgnoreCase and
compareToIgnoreCase methods for comparing strings.
– The equalsIgnoreCase and compareToIgnoreCase methods
ignore the case of the letters when comparing two strings.
• You can also use:
– str.startsWith(prefix) to check whether string str starts with a
specified prefix,
– str.endsWith(suffix) to check whether string str ends with a
specified suffix, and
– str.contains(s1) to check whether string str contains string s1 .

"Welcome to Java".startsWith("We") returns true.


"Welcome to Java".startsWith("we") returns false.
"Welcome to Java".endsWith("va") returns true.
"Welcome to Java".endsWith("v") returns false.
"Welcome to Java".contains("to") returns true.
"Welcome to Java".contains("To") returns false.
Eng. Asma Abdel Karim 17
Computer Engineering Department
Obtaining Substrings

Eng. Asma Abdel Karim 18


Computer Engineering Department
Finding a Character or a Substring in a
String

Eng. Asma Abdel Karim 19


Computer Engineering Department
Replacing and Splitting Strings

Eng. Asma Abdel Karim 20


Computer Engineering Department
Matching, Replacing and Splitting by Patterns
• A regular expression (abbreviated regex) is a
string that describes a pattern for matching a set
of strings.
• You can match, replace, or split a string by
specifying a pattern.
• At first glance, the matches method is very similar
to the equals method. For example, the following
two statements both evaluate to true:
"Java".matches("Java");
"Java".equals("Java");
• However, the matches method is more powerful.
It can match not only a fixed string, but also a set
of strings that follow a pattern.
Eng. Asma Abdel Karim 21
Computer Engineering Department
Matching, Replacing and Splitting by Patterns
(Cont.)
• For example, the following statements all evaluate to
true:
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
"Java is powerful".matches("Java.*")
• Java.* in the preceding statements is a regular
expression. It describes a string pattern that begins
with Java followed by any zero or more characters.
Here, the substring matches any zero or more
characters.
• The following statement evaluates to true.
"440-02-4534".matches("\\d{3}-\\d{2}-\\d{4}")
Here \\d represents a single digit, and \\d{3} represents
three digits.
Eng. Asma Abdel Karim 22
Computer Engineering Department
Matching, Replacing and Splitting by Patterns
(Cont.)
• The replaceAll, replaceFirst, and split methods
can be used with a regular expression.
• For example, the following statement returns
a new string that replaces $, +, or # in a+b$#c
with the string NNN.
String s = "a+b$#c".replaceAll("[$+#]", "NNN");
System.out.println(s);
– Here the regular expression [$+#] specifies a
pattern that matches $, +, or #. So, the output is
aNNNbNNNNNNc.
Eng. Asma Abdel Karim 23
Computer Engineering Department
Matching, Replacing and Splitting by Patterns
(Cont.)
• The following statement splits the string into
an array of strings delimited by punctuation
marks.
String[] tokens = "Java,C?C#,C++".split("[.,:;?]");
for (int i = 0; i < tokens.length; i++)
System.out.println(tokens[i]);
– In this example, the regular expression [.,:;?]
specifies a pattern that matches ., ,, :, ;, or ?.
– Each of these characters is a delimiter for splitting
the string. Thus, the string is split into Java, C, C#,
and C++, which are stored in array tokens.
Eng. Asma Abdel Karim 24
Computer Engineering Department
Formatting Strings
• The String class contains the static format
method to return a formatted string.
• The syntax to invoke this method is:
String.format(format, item1, item2, ..., itemk)
• This method is similar to the printf method
except that the format method returns a
formatted string, whereas the printf method
displays a formatted string.
• Example:
String s = String.format("%7.2f%6d%-4s", 45.556, 14,
"AB");
System.out.println(s);
Eng. Asma Abdel Karim 25
Computer Engineering Department
The StringBuilder and StringBuffer Classes
• In general, the StringBuilder and StringBuffer
classes can be used wherever a string is used.
• StringBuilder and StringBuffer are more flexible
than String.
– You can add, insert, or append new contents into
StringBuilder and StringBuffer objects, whereas the
value of a String object is fixed once the string is
created.
• The StringBuilder class is similar to StringBuffer
except that the methods for modifying the buffer
in StringBuffer are synchronized.
– This means that only one task is allowed to execute
the methods.
Eng. Asma Abdel Karim 26
Computer Engineering Department
The StringBuilder and StringBuffer Classes
(Constructors)

Eng. Asma Abdel Karim 27


Computer Engineering Department
The StringBuilder and StringBuffer Classes
(Modifying Strings)

Eng. Asma Abdel Karim 28


Computer Engineering Department
The StringBuilder and StringBuffer Classes
(Other Methods)

Eng. Asma Abdel Karim 29


Computer Engineering Department

You might also like