10.string handling
TRANSCRIPT
-
7/28/2019 10.String Handling
1/44
String handling
-
7/28/2019 10.String Handling
2/44
when you create a String object, you are creating astring that cannot be changed. That is, once a Stringobject has been created, you cannot change the
characters that comprise that string. At first, thismay seem to be a serious restriction.
However, such is not the case. You can still perform
all types of string operations. The difference is thateach time you need an altered version of an existingstring, a new String object is created that containsthe modifications. The original string is left
unchanged. This approach is used because fixed, immutable
strings can be implemented more efficiently thanchangeable ones.
-
7/28/2019 10.String Handling
3/44
For those cases in which a modifiable string is
desired, there is a companion class to String
called StringBuffer, whose objects containstrings that can be modified after they are
created.
the strings within objects of type String areunchangeable means that the contents of the
String instance cannot be changed after it has
been created.
However, a variable declared as a String
reference can be changed to point at some
other String object at any time.
-
7/28/2019 10.String Handling
4/44
The String Constructors
The String class supports several constructors. To create
an empty String, you call default constructor. For e.g.,
String s = new String();
will create an instance ofString with no characters in it.
Frequently, you will want to create strings that have
initial values. The String class provides a variety of
constructors to handle this. To create a String initialized
by an array of characters, use the constructor shown
here: String(char chars[ ]) Here is an example: char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string abc.
-
7/28/2019 10.String Handling
5/44
You can specify a subrange of a character array asan initializer using the following constructor:
String(char chars[ ], int startIndex, int numChars) Here, startIndexspecifies the index at which the
subrange begins, and numChars specifies thenumber of characters to use. Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };String s = new String(chars, 2, 3);
This initializes s with the characters cde.
You can construct a String object that contains thesame character sequence as another String objectusing this constructor: String(String strObj)
Here, strObjis a String object.
-
7/28/2019 10.String Handling
6/44
// Construct one String from another.
class MakeString {
public static void main(String args[]) {
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);System.out.println(s2);
}
}
The output from this program is as follows:
Java
Java
As you can see, s1 and s2 contain the same string.
-
7/28/2019 10.String Handling
7/44
Even though Javas char type uses 16 bits torepresent the Unicode character set, the typical
format for strings on the Internet uses arrays of8-bit bytes constructed from ASCII character set.
Because 8-bit ASCII strings are common, theString class provides constructors that initialize a
string when given a byte array. Their forms areshown here: String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int
numChars) In each of these constructors, the byte-to-
character conversion is done by using the defaultcharacter encoding of the platform.
-
7/28/2019 10.String Handling
8/44
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[]) {
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);System.out.println(s2);
}
}
This program generates the following output:
ABCDEF
CDE
-
7/28/2019 10.String Handling
9/44
The contents of the array are copied whenever youcreate a String object from an array.
If you modify the contents of the array after youhave created the string, the String will beunchanged.
String Length
To obtain this value, call the length( ) method,shown here: int length( )
The following fragment prints 3, since there are
three characters in the string s:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
-
7/28/2019 10.String Handling
10/44
-
7/28/2019 10.String Handling
11/44
String Concatenation :
The + operator, concatenates two strings, producing
a String object as the resultString age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);String longStr = "This could have been " +
"a very long line that would have " +
"wrapped around. But string concatenation " +"prevents this.";
System.out.println(longStr);
-
7/28/2019 10.String Handling
12/44
String Concatenation with Other Data Types
int age = 9;
String s = "He is " + age + " years old.";System.out.println(s);
In this case, age is an int rather than another String,
but the output produced is the same as before.
The int value in age is automatically converted into
its string representation within a String object
String s = "four: " + 2 + 2;
System.out.println(s);
This fragment displays - four: 22
String s = "four: " + (2 + 2);
Now s contains the string four: 4.
-
7/28/2019 10.String Handling
13/44
String Conversion and toString( )
Every class implements toString() because it is
defined by Object.
The toString( ) method has this general form:
String toString( )
To implement toString( ), simply return a Stringobject that contains the human readable string
that appropriately describes an object of your
class.
class Box { // Override toString() for Box class.
double width; double height;
double depth;
4/22/2013 13
-
7/28/2019 10.String Handling
14/44
Box(double w, double h, double d) {
width = w; height = h; depth = d; }
public String toString() {
return "Dimensions are " + width + " by " +
depth + " by " + height + "."; } }
class toStringDemo {
public static void main(String args[]) {Box b = new Box(10, 12, 14);
String s = "Box b: " + b; // concatenate Box object
System.out.println(b); // convert Box to string
System.out.println(s); } }The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.04/22/2013 14
-
7/28/2019 10.String Handling
15/44
Character Extraction:
The characters that comprise a string within a
String object cannot be indexed as if they were acharacter array. Many of the String methods
employ an index (or offset) into the string for
their operation. Like arrays, the string indexes begin at zero.
charAt( )
To extract a single character from a String referdirectly to an individual character via the charAt( )
method.
It has this general form: char charAt(int where )4/22/2013 15
-
7/28/2019 10.String Handling
16/44
where is the index of the character that you want to
obtain. The value of where must be nonnegative and
specify a location within the string.
charAt( ) returns the character at the specified
location. For example, char ch;
ch = "abc".charAt(1);
assigns the value b to ch.
getChars( )
To extract more than one character at a time, use the
getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart)4/22/2013 16
-
7/28/2019 10.String Handling
17/44
Here, sourceStart specifies the index of the beginning
of the substring, and sourceEndspecifies an index that
is one past the end of the desired substring.
The substring contains the characters from sourceStart
through sourceEnd1.
The array that will receive the characters is specified
by target.
The index within target at which the substring willbe
copied is passed in targetStart.
The target array should be large enough to hold thenumber of characters in the specified substring.
4/22/2013 17Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
18/44
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the getChars method.";int start = 10;
int end = 14;
char buf[] = new char[end - start];s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Here is the output of this program:
demo4/22/2013 18
-
7/28/2019 10.String Handling
19/44
String Comparison
equals( )
To compare two strings for equality, use equals( ).
It has this general form:
boolean equals(Object str)
str is the String object being compared with theinvoking String object.
Itreturns true if the strings contain the same
characters in the same order, and false otherwise.
The comparison is case-sensitive.
4/22/2013 19
-
7/28/2019 10.String Handling
20/44
equalsIgnoreCase( )
Comparison that ignores case differences,
equalsIgnoreCase( ) When it compares two strings, it considers A-Z to be
the same as a-z.
It has this general form:boolean equalsIgnoreCase(String str)
Here, str is the String object being compared with the
invoking String object.
Itreturns true if the strings contain the same
characters in the same order, and false otherwise.
4/22/2013 20Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
21/44
class equalsDemo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +
s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " +
s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4)); } }4/22/2013 21
-
7/28/2019 10.String Handling
22/44
The output from the program is shown here:
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
regionMatches( )
The regionMatches( ) method compares a specific
region inside a string with another specific region in
another string.
boolean regionMatches(int startIndex, String str2, intstr2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase, int
startIndex, String str2, int str2StartIndex, int numChars)
-
7/28/2019 10.String Handling
23/44
startIndex specifies the index at which the region begins
within the invoking String object.
The String being compared is specified by str2.
The indexat which the comparison will start within str2
is specified by str2StartIndex.
The length of the substring being compared is passed in
numChars.
If ignoreCase is true, the case of the characters is
ignored. Otherwise, case is significant.
startsWith( ) and endsWith( )
The startsWith( ) method determines whether a given
String begins with a specified string.
4/22/2013 23
-
7/28/2019 10.String Handling
24/44
endsWith( ) determines whether the String inquestion ends with a specified string.
boolean startsWith(String str)
boolean endsWith(String str)boolean startsWith(String str, int startIndex)
Here, str is the String being tested.
If the string matches, true is returned. Otherwise,false is returned
startIndex specifies the index into the invoking stringat which point the search will begin
"Foobar".endsWith("bar")
"Foobar".startsWith("Foo") are both true.
"Foobar".startsWith("bar", 3) returns true.4/22/2013 24
-
7/28/2019 10.String Handling
25/44
equals( ) Versus ==
The equals( ) method compares the characters
inside a String object. The == operator comparestwo object references to see whether they refer
to the same instance.
Two different String objects can contain the
same characters, but references to these objects
will not compare as equal:
The contents of the two String objects are
identical, but they are distinct objects. s1 and s2do not refer to the same objects and are,
therefore, not ==
4/22/2013 25
-
7/28/2019 10.String Handling
26/44
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 ==s2));
}
}
Output of the preceding example:
Hello equals Hello -> true
Hello == Hello -> false4/22/2013 26Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
27/44
compareTo( )
To know which is less than, equal to, or greater thanthe next
int compareTo(String str) str is the String being compared with the invoking
String.
The result of the comparison is returned and is
interpreted as shown here:Value - Meaning
Less than zero- The invoking string is less than str.
Greater than zero- The invoking string is greater
than str. Zero -The two strings are equal.
compareToIgnoreCase( )
int compareToIgnoreCase(String str)4/22/2013 27Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
28/44
// A bubble sort for Strings.
class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men", "to",
"come", "to", "the", "aid", "of", "their", "country };
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t; } }
System.out.println(arr[j]);
} } }
-
7/28/2019 10.String Handling
29/44
Searching Strings indexOf( )
lastIndexOf( ) The methods return the index at which the character or
substring was found, or1 on failure.
To search for the first occurrence of a character, use
int indexOf(int ch) To search for the last occurrence of a character, use
int lastIndexOf(int ch)
ch is the character being sought.
To search for the first or last occurrence of a substring, useint indexOf(String str)
int lastIndexOf(String str)
str specifies the substring.4/22/2013 29Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
30/44
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
Here, startIndexspecifies the indexat which
point the search begins.
ForindexOf( ), the search runs from startIndex
to the end of the string.
ForlastIndexOf( ), the search runs from
lastIndexto zero.4/22/2013 30Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
31/44
Modifying a String
To modify a String either copy it into a StringBuffer
or use one of the following String methods, whichwill construct a new copy of the string.
substring( )
String substring(int startIndex) startIndexspecifies the index at which the substring
will begin.
It returns a copy of the substring that begins at
startIndexand runs to the end of the invoking string.
4/22/2013 31Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
32/44
String substring(int startIndex, int endIndex)
startIndex specifies the beginning index, and endIndex
specifies the stopping point.
The string returned contains all the characters from
the beginning index, up to, but not including, the
ending index.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String search = "is";String sub = "was";
String result = "";
int i;4/22/2013 32Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
33/44
do { // replace all matching substrings
System.out.println(org);
i = org.indexOf(search);
if(i != -1) {
result = org.substring(0, i);
result = result + sub;
result = result + org.substring(i + search.length());
org = result; }
} while(i != -1); } }
The output from this program is shown here:
This is a test. This is, too.Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.4/22/2013 33Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
34/44
concat( )
String concat(String str)
This method creates a new object that contains theinvoking string with the contents ofstr appended tothe end.
concat( )performs the same function as +.
String s1 = "one";
String s2 = s1.concat("two");
Puts the string onetwo into s2.
It generates the same result as the followingsequence:
String s1 = "one";
String s2 = s1 + "two";4/22/2013 34Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
35/44
replace( )
The replace( ) method replaces all occurrences ofone character in the invoking string with anothercharacter.
It has the following general form:
String replace(char original, char replacement)
original specifies the character to be replaced bythe character specified by replacement.
The resulting string is returned.
String s = "Hello".replace('l', 'w');
puts the string Hewwo into s.
4/22/2013 35Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
36/44
trim( )
The trim( ) method returns a copy of theinvoking string from which any leading and
trailing whitespace has been removed.
It has this general form:
String trim( )
String s = " Hello World ".trim();
This puts the string Hello World into s.
4/22/2013 36Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
37/44
Changing the Case of Characters Within a String
The method toLowerCase( ) converts all the
characters in a string from uppercase to lowercase. The toUpperCase( ) method converts all the
characters in a string from lowercase to uppercase.
Nonalphabetical characters, such as digits, areunaffected.
String toLowerCase( )
String toUpperCase( ) Both methods return a String object that contains
the uppercase or lowercase equivalent of the
invoking String.4/22/2013 37Smitha N. Pai CSE Dept.
i j il *
-
7/28/2019 10.String Handling
38/44
import java.util.*;
public class CurrentTime{
public static void main(String[] args){
Calendar calendar = new GregorianCalendar();String am_pm;
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
if(calendar.get(Calendar.AM_PM) == 0)
am_pm = "AM";
else
am_pm = "PM";
System.out.println("Current Time : " + hour + ":"
+ minute + ":" + second + " " + am_pm);
} }4/22/2013 38Smitha N. Pai CSE Dept.
-
7/28/2019 10.String Handling
39/44
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class DateUtils { public static final StringDATE_FORMAT_NOW = "yyyy-MM-ddHH:mm:ss";
public static String now() { Calendar cal =
Calendar.getInstance();
SimpleDateFormat sdf = newSimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime()); }public static void main(String arg[]) {
System.out.println("Now : " + DateUtils.now()); }
}4/22/2013 Smitha N. Pai CSE Dept. 39
-
7/28/2019 10.String Handling
40/44
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class DateUtils { public static String now(String dateFormat) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(cal.getTime()); }
public static void main(String arg[]) {
System.out.println(DateUtils.now("dd MMMMM yyyy"));
System.out.println(DateUtils.now("yyyyMMdd"));
System.out.println(DateUtils.now("dd.MM.yy"));
System.out.println(DateUtils.now("MM/dd/yy"));
System.out.println(DateUtils.now
("yyyy.MM.dd G 'at' hh:mm:ss z"));
System.out.println(DateUtils.now("EEE, MMM d, ''yy"));
4/22/2013 Smitha N. Pai CSE Dept. 40
-
7/28/2019 10.String Handling
41/44
System.out.println(DateUtils.now("h:mm a"));
System.out.println(DateUtils.now("H:mm:ss:SSS"));
System.out.println(DateUtils.now("K:mm a,z"));
System.out.println(DateUtils.now("yyyy.MMMMM.dd
GGG hh:mm aaa"));
} }
import java.util.Date;class DateDemo {
public static void main(String args[]) {
// Instantiate a Date objectDate date = new Date();
// display time and date //using toString()
System.out.println(date.toString()); } }4/22/2013 Smitha N. Pai CSE Dept. 41
-
7/28/2019 10.String Handling
42/44
// Demonstrate GregorianCalendar
import java.util.*;
class GregorianCalendarDemo {
public static void main(String args[]) {
String months[] = {
"Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
int year;
// Create a Gregorian calendar initialized// with the current date and time in the
// default locale and timezone.
GregorianCalendar gcalendar = new GregorianCalendar();
// Display current time and date information.
-
7/28/2019 10.String Handling
43/44
System.out.print("Date: ");System.out.print(months[gcalendar.get(Calendar.MONT
H)]);
System.out.print(" " + gcalendar.get(Calendar.DATE) + "
");
System.out.println(year =
gcalendar.get(Calendar.YEAR));
System.out.print("Time: ");System.out.print(gcalendar.get(Calendar.HOUR) + ":");
System.out.print(gcalendar.get(Calendar.MINUTE) +
":");
System.out.println(gcalendar.get(Calendar.SECOND));// Test if the current year is a leap year
if(gcalendar.isLeapYear(year)) {
System.out.println("The current year is a leap year");
}
-
7/28/2019 10.String Handling
44/44
else {
System.out.println("The current year is not a
leap year");}
}
}
Sample output is shown here:
Date: Jan 1 2007
Time: 11:25:27
The current year is not a leap year