Chapter 10 – Strings and Characters

Download Report

Transcript Chapter 10 – Strings and Characters

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
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.
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);
4
Example
// StringConstructors.java
// This program demonstrates the String class constructors.
public class StringConstructors {
public static void main (String args[]) {
char charArray[] = { 'b',
'd',
byte byteArray[] = { 'n',
'y',
StringBuffer buffer;
String s, s1, s2, s3, s4,
'i',
'a',
'e',
'e',
'r', 't', 'h', ' ',
'y' };
'w', ' ',
'a', 'r' };
s5, s6, s7;
s = new String( "hello" );
buffer = new StringBuffer();
buffer.append( "Welcome to Java Programming!" );
//
s1
s2
s3
s4
s5
s6
s7
use the String constructors
= new String();
= new String( s );
= new String( charArray );
= new String( charArray, 6, 3 );
= new String( byteArray, 4, 4 );
= new String( byteArray );
= new String( buffer );
5
System.out.println(
System.out.println(
System.out.println(
System.out.println(
System.out.println(
System.out.println(
System.out.println(
"s1
"s2
"s3
"s4
"s5
"s6
"s7
=
=
=
=
=
=
=
"
"
"
"
"
"
"
+
+
+
+
+
+
+
}
}
Output
s1
s2
s3
s4
s5
s6
s7
=
=
=
=
=
=
=
hello
birth day
day
year
new year
Welcome to Java Programming!
s1
s2
s3
s4
s5
s6
s7
);
);
);
);
);
);
);
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.
6
7
Example
public 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 StringMiscellaneous
s1: hello there
Length of s1: 11
The string reversed is:
e r e h t
o l l e h
The character array is:
there
8
Comparing Strings
• You CANNOT use relational operators like ==, <= to
compare two Strings.
• String class provides the following methods for comparing
two strings
public 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.
9
Example
public 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 StringCompare
s1 = hello
s2 = good bye
s3 = Happy Birthday
s4 = happy birthday
s1 equals "hello"
s1 does not equal "hello"
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 StringCompare
s1 = hello
s2 = good bye
s3 = Happy Birthday
s4 = happy birthday
.......
s3 equals s4
s1.compareTo( s2 ) is 1
s2.compareTo( s1 ) is -1
s1.compareTo( s1 ) is 0
s3.compareTo( s4 ) is -32
s4.compareTo( s3 ) is 32
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.
12
Example
public 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";
>java StringStartEnd
System.out.print( output );
"started" starts with "st"
"starting" starts with "st"
// end class StringStartEnd
"started" ends with "ed"
"ended" ends with "ed"
13
Locating 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
public int indexOf(int
ch);
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.
14
Example
class 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" ) );
15
Output
letters = "abcdefghijklmabcdefghijklm";
>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 16
Last "def" is located at index 3
Last "hello" is located at index -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 endIndexbeginIndex.
• 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"
17
Example
class 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"
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
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 = HELLO
s2 after toLowerCase = good bye
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
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
System.out.print(String.valueOf(true));
System.out.print(String.valueOf(12000));
System.out.print(String.valueOf('A'));
System.out.print(String.valueOf(24.72));
Output
true
12000
A
24.72
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 S2
Substring from index 5 to end is "llo World!
s after trim = "Hello World!"
s = "
Hello World!
"
"
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.
24
import javax.swing.*;
class CapName {
public static void main (String args[]) {
String inName;
String outName;
int spaceLoc;
Michael Jackson
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);
}
}
25
Command Line Arguments
• public static void main(String args[])
What does this parameter mean?
• 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.
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 Chan
Hello
Peter
Chan
>java CommandLineArgument "Hello Peter Chan" "Hello Mary Wong"
Hello Peter Chan
Hello Mary Wong
One string object
27
Example 2
• Write a program to sum up two command line arguments.
>java AddTwoIntegers
Usage : java AddTwoIntegers <num1> <num2>
>java AddTwoIntegers 23 55
The sum is 78
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));
}
}
28
Exercise
• Write a program to sum up all command line arguments.
>java AddIntegers
The sum is 0
>java AddIntegers 22 35
The sum is 57
>java AddIntegers 12 3 5 26
The sum is 44