28
1 Chapter 8 – Strings and Characters 1 Introduction String and character processing – Class java.lang.String – Class java.lang.StringBuffer – Class java.lang.Character – Class java.util.StringTokenizer

Chapter 8 – Strings and Characters 1

  • Upload
    ban

  • View
    56

  • Download
    0

Embed Size (px)

DESCRIPTION

Chapter 8 – Strings and Characters 1. Introduction. String and character processing Class java.lang.String Class java.lang.StringBuffer Class java.lang.Character Class java.util.StringTokenizer. Fundamentals of Strings. String Series of characters treated as single unit - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 8 – Strings and Characters 1

1

Chapter 8 – Strings and Characters 1

Introduction

• String and character processing– Class java.lang.String– Class java.lang.StringBuffer– Class java.lang.Character– Class java.util.StringTokenizer

Page 2: Chapter 8 – Strings and Characters 1

2

Fundamentals of Strings

• String– Series of characters treated as single unit– May include letters, digits, etc.– Object of class String– You should refer to http://java.sun.com for the API details– Once created the content stored in a String object cannot

be changed (immutable).

• Java provides a rich library for manupilating Strings.

Page 3: Chapter 8 – Strings and Characters 1

3

String Constructors

• String has the following constructors:

public String();

public String(byte ascii[]);

public String(byte ascii[], int offset, int count);

public String(char value[]);

public String(char value[], int offset, int count);

public String(String value);

public String(StringBuffer buffer);

Page 4: Chapter 8 – Strings and Characters 1

4

Example// StringConstructors.java// This program demonstrates the String class constructors.

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

char charArray[] = { 'b', 'i', 'r', 't', 'h', ' ', 'd', 'a', 'y' }; byte byteArray[] = { 'n', 'e', 'w', ' ', 'y', 'e', 'a', 'r' }; StringBuffer buffer; String s, s1, s2, s3, s4, s5, s6, s7;

s = new String( "hello" ); buffer = new StringBuffer(); buffer.append( "Welcome to Java Programming!" );

// use the String constructors s1 = new String(); s2 = new String( s ); s3 = new String( charArray ); s4 = new String( charArray, 6, 3 ); s5 = new String( byteArray, 4, 4 ); s6 = new String( byteArray ); s7 = new String( buffer );

Page 5: Chapter 8 – Strings and Characters 1

5

System.out.println( "s1 = " + s1 ); System.out.println( "s2 = " + s2 ); System.out.println( "s3 = " + s3 ); System.out.println( "s4 = " + s4 ); System.out.println( "s5 = " + s5 ); System.out.println( "s6 = " + s6 ); System.out.println( "s7 = " + s7 ); }}

Output

s1 =s2 = hellos3 = birth days4 = days5 = years6 = new years7 = Welcome to Java Programming!

Page 6: Chapter 8 – Strings and Characters 1

6

String Methods length, charAt and getChars

• Method length– Determine String length

• Like arrays, Strings always “know” their size• Unlike array, Strings do not have length instance variable

• Method charAt– Get character at specific location in String – Like array, the first character begins with index 0

• Method getChars– Get entire set of characters in String – void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin);

– Copies characters from this string into the destination char array. The first character to be copied is at index srcBegin; the last character to be copied is at index srcEnd-1.

Page 7: Chapter 8 – Strings and Characters 1

7

Examplepublic class StringMiscellaneous { public static void main( String args[] ){ String s1, output = ""; char charArray[] = new char[ 5 ];; s1 = new String( "hello there" );

// output the string System.out.println("s1: " + s1);

// test length method System.out.println("Length of s1: " + s1.length());

// loop through characters in s1 and display reversed System.out.println("The string reversed is: ");

for ( int count = s1.length() - 1; count >= 0; count-- ) System.out.print( s1.charAt(count) + " " );

// copy characters from string into char array s1.getChars( 6, 11, charArray, 0 ); System.out.println("\nThe character array is: ");

for ( int count = 0; count < charArray.length; count++ ) output += charArray[ count ];

System.out.println(output); }} // end class StringMiscellaneous

>java StringMiscellaneouss1: hello thereLength of s1: 11The string reversed is:e r e h t o l l e hThe character array is:there

Page 8: Chapter 8 – Strings and Characters 1

8

Comparing Strings

• You CANNOT use relational operators like ==, <= to compare two Strings.

• String class provides the following methods for comparing two stringspublic int compareTo(String anotherString);

Returns the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

public boolean equals(Object anObject);Returns true if the Strings are equal; false otherwise.

public boolean equalsIgnoreCase(String anotherString); Returns true if the argument is not null and the Strings are equal, ignoring case; false otherwise.

Page 9: Chapter 8 – Strings and Characters 1

9

Examplepublic class StringCompare {

public static void main(String args[]){ String s1, s2, s3, s4, output;

s1 = new String( "hello" ); s2 = new String( "good bye" ); s3 = new String( "Happy Birthday" ); s4 = new String( "happy birthday" );

output = "s1 = " + s1 + "\ns2 = " + s2 + "\ns3 = " + s3 + "\ns4 = " + s4 + "\n\n";

// test for equality if ( s1.equals( "hello" ) ) output += "s1 equals \"hello\"\n"; else output += "s1 does not equal \"hello\"\n";

// test for equality with == if ( s1 == "hello" ) output += "s1 equals \"hello\"\n"; else output += "s1 does not equal \"hello\"\n";

>java StringCompares1 = hellos2 = good byes3 = Happy Birthdays4 = happy birthday

s1 equals "hello"s1 does not equal "hello"

Page 10: Chapter 8 – Strings and Characters 1

10

Example // test for equality (ignore case) if ( s3.equalsIgnoreCase( s4 ) ) output += "s3 equals s4\n"; else output += "s3 does not equal s4\n";

// test compareTo output += "\ns1.compareTo( s2 ) is " + s1.compareTo( s2 ) + "\ns2.compareTo( s1 ) is " + s2.compareTo( s1 ) + "\ns1.compareTo( s1 ) is " + s1.compareTo( s1 ) + "\ns3.compareTo( s4 ) is " + s3.compareTo( s4 ) + "\ns4.compareTo( s3 ) is " + s4.compareTo( s3 ) + "\n\n";

System.out.print( output ); }}

>java StringCompares1 = hellos2 = good byes3 = Happy Birthdays4 = happy birthday.......s3 equals s4

s1.compareTo( s2 ) is 1s2.compareTo( s1 ) is -1s1.compareTo( s1 ) is 0s3.compareTo( s4 ) is -32s4.compareTo( s3 ) is 32

Page 11: Chapter 8 – Strings and Characters 1

11

StartsWith and EndsWith

• boolean startsWith(String prefix)

– Tests if this string starts with the specified prefix.

• boolean endsWith(String suffix)

– Tests if this string ends with the specified suffix.

Page 12: Chapter 8 – Strings and Characters 1

12

Examplepublic class StringStartEnd { public static void main( String args[] ) { String strings[] = { "started", "starting", "ended", "ending" }; String output = "";

// test method startsWith for ( int count = 0; count < strings.length; count++ )

if ( strings[ count ].startsWith( "st" ) ) output += "\"" + strings[ count ] + "\" starts with \"st\"\n";

output += "\n";

// test method endsWith for ( int count = 0; count < strings.length; count++ )

if ( strings[ count ].endsWith( "ed" ) ) output += "\"" + strings[ count ] + "\" ends with \"ed\"\n";

System.out.print( output ); }

} // end class StringStartEnd

>java StringStartEnd"started" starts with "st""starting" starts with "st"

"started" ends with "ed""ended" ends with "ed"

Page 13: Chapter 8 – Strings and Characters 1

13Locating Characters and Substrings in Strings

• To locate a character or a substring in a String Object, you can use the overloaded indexOf()and lastIndexOf()

public int indexOf(int ch);

public int indexOf(int ch, int fromIndex);

the index of the first occurrence of the character in the character sequence represented by this object that is greater than or equal to fromIndex, or -1 if the character does not occur.

public int indexOf(String str);

public int indexOf(String str, int fromIndex);

public int lastIndexOf(int ch);

public int lastIndexOf(int ch, int fromIndex);

public int lastIndexOf(String str);

public int lastIndexOf(String str, int fromIndex);

If the string argument occurs as a substring within this object at a starting index no greater than fromIndex then the index of the first character of the last such substring is returned. If it does not occur as a substring starting at fromIndex or earlier, -1 is returned.

Page 14: Chapter 8 – Strings and Characters 1

14

Exampleclass StringIndexMethods { public static void main (String args[]) {

String letters = "abcdefghijklmabcdefghijklm";

// test indexOf to locate a character in a string System.out.println("'c' is located at index " + letters.indexOf('c') );

System.out.println("'a' is located at index " + letters.indexOf('a', 1 ) );

System.out.println("'$' is located at index " + letters.indexOf('$' ) );

System.out.println();

// test lastIndexOf to find a substring in a string System.out.println("Last \"def\" is located at index " + letters.lastIndexOf( "def" ) );

System.out.println("Last \"def\" is located at index " + letters.lastIndexOf( "def", 10 ) );

System.out.println("Last \"hello\" is located at index " + letters.lastIndexOf( "hello" ) ); }}

Page 15: Chapter 8 – Strings and Characters 1

15

Output

>java StringIndexMethods'c' is located at index 2'a' is located at index 13'$' is located at index -1

Last "def" is located at index 16Last "def" is located at index 3Last "hello" is located at index -1

letters = "abcdefghijklmabcdefghijklm";

Page 16: Chapter 8 – Strings and Characters 1

16

Extracting Substrings from Strings• String class provides the following methods for extracting

substrings:public String substring(int beginIndex);

public String substring(int beginIndex, int endIndex);

Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

• Example: if s = "hamburger",

– s.substring(3) returns "burger"

– s.substring(6) returns "ger"

– s.substring(9) returns "" (an empty string)

– s.substring(4, 8) returns "urge"

– s.substring(1, 3) returns "am"

Page 17: Chapter 8 – Strings and Characters 1

17

Exampleclass StringSubstring { public static void main (String args[]) {

String letters = "abcdefghijklmabcdefghijklm";

// test substring System.out.println( "\nSubstring from index 20 to end is " + "\"" + letters.substring( 20 ) + "\"");

System.out.println( "Substring from index 0 upto 6 is " + "\"" + letters.substring( 0, 6 ) + "\""); }}

>java StringSubstring

Substring from index 20 to end is "hijklm"Substring from index 0 upto 6 is "abcdef"

Page 18: Chapter 8 – Strings and Characters 1

18

Miscellaneous String Methods

• String class has several methods that return modified copies of a string object to a character array:– public String concat(String str);

– public String replace(char oldChar, char newChar);• returns a string derived from this string by replacing every

occurrence of oldChar with newChar.

– public char[] toCharArray();

– public String toLowerCase();

– public String toString();

– public String toUpperCase();

– public String trim(); • returns this string, with whitespace removed from the front and

end

Page 19: Chapter 8 – Strings and Characters 1

19

Example

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

String s1 = new String( "hello" ), s2 = new String( "GOOD BYE" ), s3 = new String( " spaces " );

System.out.println( );

// test method replace System.out.println( "Replace 'l' with 'L' in s1: " + s1.replace( 'l', 'L' ) ); System.out.println( );

// test toLowerCase and toUpperCase System.out.println( "s1 after toUpperCase = " + s1.toUpperCase() ); System.out.println( "s2 after toLowerCase = " + s2.toLowerCase() ); System.out.println( );

>java StringMisc

Replace 'l' with 'L' in s1: heLLo

s1 after toUpperCase = HELLOs2 after toLowerCase = good bye

Page 20: Chapter 8 – Strings and Characters 1

20

Example

// test trim method System.out.println( "s3 after trim = \"" + s3.trim() + "\""); System.out.println( );

// test toString method System.out.println( "s1 = " + s1.toString() ); System.out.println( );

// test toCharArray method char charArray[] = s1.toCharArray(); System.out.println( "s1 as a character array = " ); for ( int i = 0; i < charArray.length; i++ ) { System.out.print( charArray[i]); // use method print(char) System.out.print( " " ); } System.out.println(); }}

>java StringMisc.......

s3 after trim = "spaces"

s1 = hello

s1 as a character array =h e l l o

Page 21: Chapter 8 – Strings and Characters 1

21

Using String Method valueOf• Java provides a set of static valueOf methods that takes

arguments of various types, convert those arguments to strings and return them as String objects.– public static String valueOf(boolean b);

– public static String valueOf(char c);

– public static String valueOf(char data[]);

– public static String valueOf(char data[], int offset, int count);

– public static String valueOf(double d);

– public static String valueOf(float f);

– public static String valueOf(int i);

Code Output System.out.print(String.valueOf(true)); true System.out.print(String.valueOf(12000)); 12000 System.out.print(String.valueOf('A')); A System.out.print(String.valueOf(24.72)); 24.72

Page 22: Chapter 8 – Strings and Characters 1

22

Important!

• All the above String methods do NOT modify the String itself. It just return a NEW String objects.

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

String s = " Hello World! ";

// test substring System.out.println( "\nSubstring from index 5 to end is " + "\"" + s.substring( 5 ) + "\""); System.out.println( "s after trim = \"" + s.trim() + "\"");

System.out.println( "s = \"" + s + "\""); }}

>java S2Substring from index 5 to end is "llo World! "s after trim = "Hello World!"s = " Hello World! "

Page 23: Chapter 8 – Strings and Characters 1

23

Example• Write a program that asks for user's name (always consists of

two names) and then writes it back with the first name as entered, and the second name in capital letters.

Page 24: Chapter 8 – Strings and Characters 1

24

import javax.swing.*;

class CapName { public static void main (String args[]) { String inName; String outName; int spaceLoc;

inName = JOptionPane.showInputDialog("Enter your name:");

// find space spaceLoc = inName.indexOf(' ');

// get first name and last name outName = inName.substring(0, spaceLoc) + " " + inName.substring(spaceLoc+1).toUpperCase();

JOptionPane.showMessageDialog(null, "Welcome, " + outName); System.exit(0);

}}

Michael Jackson

spaceLoc

Page 25: Chapter 8 – Strings and Characters 1

25

Command Line Arguments

• When runs an application, you can supply a list of arguments - command line argument

• The arguments are passed as an array of String (args in the above example) to the main method.

• public static void main(String args[])

What does this parameter mean?

Page 26: Chapter 8 – Strings and Characters 1

26

Example 1

import java.util.*;

public class CommandLineArgument { public static void main( String args[] ) { for (int i=0; i<args.length; i++) {

System.out.println(args[i]); }

}}

>java CommandLineArgument

>java CommandLineArgument Hello Peter ChanHelloPeterChan

>java CommandLineArgument "Hello Peter Chan" "Hello Mary Wong"Hello Peter ChanHello Mary Wong

One string object

Page 27: Chapter 8 – Strings and Characters 1

27

Example 2

import java.util.*;

public class AddTwoIntegers { public static void main( String args[] ) { int num1, num2; if (args.length != 2) { System.out.println( "Usage : java AddTwoIntegers <num1> <num2>" ); System.exit(0); }

num1 = Integer.parseInt(args[0]); num2 = Integer.parseInt(args[1]);

System.out.println("The sum is " + (num1+num2)); }}

>java AddTwoIntegersUsage : java AddTwoIntegers <num1> <num2>

>java AddTwoIntegers 23 55The sum is 78

• Write a program to sum up two command line arguments.

Page 28: Chapter 8 – Strings and Characters 1

28

Exercise

>java AddIntegersThe sum is 0

>java AddIntegers 22 35The sum is 57

>java AddIntegers 12 3 5 26The sum is 44

• Write a program to sum up all command line arguments.