string handling java

Upload: evanpaul90

Post on 04-Apr-2018

234 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 String handling java

    1/43

    FOR MORE SLIDES, ASSIGNMENTS AND STUDY MATERIALS VISIT

    www.techahoy.in

  • 7/29/2019 String handling java

    2/43

    String handling

  • 7/29/2019 String handling java

    3/43

    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/29/2019 String handling java

    4/43

    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/29/2019 String handling java

    5/43

    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/29/2019 String handling java

    6/43

    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/29/2019 String handling java

    7/43

    // 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/29/2019 String handling java

    8/43

    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/29/2019 String handling java

    9/43

    // 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/29/2019 String handling java

    10/43

    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/29/2019 String handling java

    11/43

    Special String Operations

    String Literals

    char chars[] = { 'a', 'b', 'c' };String s1 = new String(chars);

    String s2 = "abc"; // use string literal

    String object is created for every string literal,you can use a string literal any place you canuse a String object.

    Call methods directly on a quoted string as if it

    were an object referenceSystem.out.println("abc".length());

    3/17/2011 11

  • 7/29/2019 String handling java

    12/43

    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/29/2019 String handling java

    13/43

    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/29/2019 String handling java

    14/43

    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;

    3/17/2011 14

  • 7/29/2019 String handling java

    15/43

    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.03/17/2011 15

  • 7/29/2019 String handling java

    16/43

    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 )3/17/2011 16

  • 7/29/2019 String handling java

    17/43

    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)3/17/2011 17

  • 7/29/2019 String handling java

    18/43

    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.

    3/17/2011 18Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    19/43

    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:

    demo3/17/2011 19

  • 7/29/2019 String handling java

    20/43

    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.

    3/17/2011 20

  • 7/29/2019 String handling java

    21/43

    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.

    3/17/2011 21Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    22/43

    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)); } }3/17/2011 22

  • 7/29/2019 String handling java

    23/43

    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/29/2019 String handling java

    24/43

    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.

    3/17/2011 24

  • 7/29/2019 String handling java

    25/43

    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.3/17/2011 25

  • 7/29/2019 String handling java

    26/43

    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 ==

    3/17/2011 26

  • 7/29/2019 String handling java

    27/43

    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 -> false3/17/2011 27Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    28/43

    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)3/17/2011 28Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    29/43

    // 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/29/2019 String handling java

    30/43

    Searching Strings indexOf( )

    lastIndexOf( )

    The methods return the index at which the character orsubstring 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.3/17/2011 30Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    31/43

    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.3/17/2011 31Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    32/43

    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.

    3/17/2011 32Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    33/43

    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;3/17/2011 33Smitha N. Pai CSE Dept.

    //

  • 7/29/2019 String handling java

    34/43

    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.3/17/2011 34Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    35/43

    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";3/17/2011 35Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    36/43

    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.

    3/17/2011 36Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    37/43

    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.

    3/17/2011 37Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    38/43

    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.3/17/2011 38Smitha N. Pai CSE Dept.

    i j il *

  • 7/29/2019 String handling java

    39/43

    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);

    } }3/17/2011 39Smitha N. Pai CSE Dept.

  • 7/29/2019 String handling java

    40/43

    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()); }

    }3/17/2011 Smitha N. Pai CSE Dept. 40

  • 7/29/2019 String handling java

    41/43

    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"));

    3/17/2011 Smitha N. Pai CSE Dept. 41

  • 7/29/2019 String handling java

    42/43

    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()); } }3/17/2011 Smitha N. Pai CSE Dept. 42

  • 7/29/2019 String handling java

    43/43

    FOR MORE SLIDES, ASSIGNMENTS AND STUDY MATERIALS VISIT

    www.techahoy.in