29
Strings Chapter 7

Strings Chapter 7. An object of the String class represents a string of characters. The String class belongs to the java.lang package, which does

Embed Size (px)

Citation preview

Page 1: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Strings

Chapter 7

Page 2: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

An object of the String class represents a string of characters.

The String class belongs to the java.lang package, which does not require an import statement.

Like other classes, String has constructors and methods.

Page 3: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

string: An object storing a sequence of text characters. Two ways to create a string

As a new object through the String class

String name = new String("text");

Convenient shorthand method

String name = "text";

Page 4: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

immutable. String name = "text"; Once created in memory, a string cannot be changed:

none of its methods changes the string If a string variable is reassigned, the memory address is

deleted and a new memory address is created

Immutable objects are convenient because several references can point to the same object safely: there is no danger of changing an object through one reference without the others being aware of the change.

Page 5: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Uses less memory.

String word1 = "Java"; String word2 = word1;

String word1 = “Java";String word2 = new String(word1);

word1

OKLess efficient: wastes memory

"Java"

"Java"

"Java"

word2

word1

word2

Page 6: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Less efficient — you need to create a new string and throw away the old one even for small changes.

String word = "java"; word = "HTML";

word "java"

"HTML"

Page 7: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Character class Contains standard methods for testing values of

characters Methods that begin with “is”

Such as isUpperCase() Return Boolean value Can be used in comparison statements

Methods that begin with “to” Such as toUpperCase() Return character that has been converted to stated format

Page 8: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Characters of a string are numbered with 0-based indexes:

String name = "Java fun";

First character's index : 0 Last character's index : 1 less than the string's length

The individual characters are values of type char

index 0 1 2 3 4 5 6 7

character J a v a f u n

Page 9: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

These methods are called using the dot notation:String name = "Hello World";System.out.println(name.length());

Method name Description

indexOf(str) index where the start of the given string appears in this string (-1 if not found)

length() number of characters in this string

substring(index1, index2)orsubstring(index1)

the characters in this string from index1 (inclusive) to index2 (exclusive);

if index2 is omitted, grabs till end of string

toLowerCase() a new string with all lowercase letters

toUpperCase() a new string with all uppercase letters

charAt(index) Returns the character at the specified index

Page 10: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

It is sometimes useful to determine the length of a string

Use the length( ) methods

String s = "Java is Fun";int sLength = s.length();System.out.println(sLength); // 11

The method counts the number of characters in the string variable. It produces an integer result.

Page 11: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Java is case sensitive

String s1 = "Java";String s2 = "java";

s1 and s2 represent two different strings

To get around this possible obstacle, Java has methods that display a string in all upper case letters or all lower case letters toUpperCase( ) toLowerCase( )

Page 12: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

These methods build and return a new string, rather than modifying the current string.

To modify a variable's value, you must reassign it:

String s = "Hello World";s1 = s.toUpperCase();s2 = s.toLowerCase();System.out.println(s1 + " " + s2);

// HELLO WORLD hello world

Page 13: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Another common task when handling strings is to see whether one string can be found inside another. This is useful when you are looking for a specific text inside a large string (such as a document)

To look inside a string, use indexOf( string )

If string is found, an integer that represents the starting position of the first occurrence is returned

If string is not found, -1 is returned lastIndexOf( string )

Returns the position of the last occurrence

String s = "Java is fun";int sfind = s.indexOf("fun");System.out.println(sfind); // 8

Page 14: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

// index 012345678901234567890123456

String name = "President George Washington";

name.indexOf ('P'); 0

name.indexOf ('e'); 2

name.indexOf ("George"); 10

name.indexOf ('e', 3); 6

name.indexOf ("Bob"); -1

name.lastIndexOf ('e'); 15

Returns:

(not found)

(starts searching at position 3)

Page 15: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

We may also want to find and replace parts of a large string

There are a few replace methods available replace(oldString, newString) replaceFirst(oldString, newString) replaceAll(oldString, newString)

String s = "Java is fan";s1 = s.replace("fan","fun");System.out.println(s1);

// Java is fun

Page 16: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

// index 01234567890String s1 = "Hello World";

System.out.println(s1.length()); System.out.println(s1.indexOf("r"));System.out.println(s1.charAt(1));System.out.println(s1.substring(3, 7));

String s2 = s1.substring(0, 5);System.out.println(s2.toLowerCase());

118elo Whello

Page 17: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

One thing we will be testing often in our programs is whether one string is the same as the other

Two basic commands: equals( ) compareTo( )

Do not compare two Strings using the == operator Not comparing values Comparing computer memory locations

Page 18: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

equals() method Evaluates contents of two String objects to determine

if they are equivalent Returns true if objects have identical contents

equalsIgnoreCase() method Ignores case when determining if two Strings

equivalent Useful when users type responses to prompts in

programs

s1 = "Java";s2 = "java";boolean eq = s1.equals(s2);System.out.println(eq); // false

Page 19: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

compareTo() method Compares two Strings and returns:

Zero Only if two Strings refer to same value

Negative number If calling object “less than” argument

Positive number If calling object “more than” argument

Page 20: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

These methods return a boolean value (true or false)

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

Page 21: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Concatenation Join multiple variables together Two ways to concatenate

concat method String s3 = s1.concat(s2);

Convenient shorthand String s3 = s1 + s2;

s1 = "Hello";s2 = "World";s3 = s1 + " " + s2;

Page 22: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Three ways to convert a number into a string:

1. String s = "" + num;

2. String s = Integer.toString (i);

String s = Double.toString (d);

3. String s = String.valueOf (num);

Integer and Double are “wrapper” classes from java.lang that represent numbers as objects. They also provide useful static methods.

s = String.valueOf(123); //"123"

s = "" + 123; //"123"

s = Integer.toString(123); //"123"s = Double.toString(3.14); //"3.14"

Page 23: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Integer and Double class Automatically imported into programs (java.lang) Convert String to integer

valueOf() method Convert String to Integer class object

intValue() method Extract simple integer from wrapper class

parseInt() method Returns its integer value

Convert String to double parseDouble() method

Returns its double value

Page 24: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

The StringBuilder/StringBuffer class is an alternative to the String class.

Can be used wherever a string is used.

More flexible than String. You can add, insert, or append new contents into

a string buffer, whereas the value of a String object is fixed once the string is created.

Page 25: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Using StringBuilder objects Provides improved computer performance over String

objects Can insert or append new contents into StringBuilder

StringBuilder constructorspublic StringBuilder ()public StringBuilder (int capacity)public StringBuilder (String s)

StringBuilder name = new StringBuilder("Hello");

Page 26: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Method Description

append(str) Adds a string to the end of the StringBuilder object

delete(start, end) Deletes characters at the specified index

insert(index, str) Inserts string into the builder at the position offset

replace(start, end, str) Replaces the characters in this builder at the specified index with the specified string

setCharAt(index, char) Changes a character at the specified index

CharAt(index) Returns character at the specified index

Page 27: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

Write a program to check whether a string is a palindrome: a string that reads the same

forward and backward.civicradarlevelrotor kayak reviver racecar redder

Page 28: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

import java.util.Scanner;

public class CheckPalindrome {public static void main(String[] args) {

Scanner input = new Scanner(System.in);System.out.print("Enter a string: ");String s = input.nextLine();

if (isPalindrome(s)) System.out.println(s + " is a palindrome");

else System.out.println(s + " is not a palindrome");

}

// continued on next page

Page 29: Strings Chapter 7.  An object of the String class represents a string of characters.  The String class belongs to the java.lang package, which does

public static boolean isPalindrome(String s) {

// Set index of the first and last characters in the stringint low = 0;int high = s.length() - 1;

while (low < high) { if (s.charAt(low) != s.charAt(high))

return false; // Not a palindrome low++;

high--; }

return true; // The string is a palindrome }}