Operations on Strings

Embed Size (px)

Citation preview

  • 8/8/2019 Operations on Strings

    1/36

    Operations on String

    Joining Strings

    tring myString = The quick brown fox +

    String date = 31st ;String month = December;String lastDay = date + month;// Result

    String phrase = Toomany;

  • 8/8/2019 Operations on Strings

    2/36

    Example I (String

    JoinStrings.javaTestConcat.java

    conc Concatenates 2

  • 8/8/2019 Operations on Strings

    3/36

  • 8/8/2019 Operations on Strings

    4/36

    The conversion of values ofthe basic types to type Stringis actually accomplished byusing a static method,toString(), of a standard class

    that corresponds to the basictype (wrapper class).

    BasicType

    WrapperClass

    byte Byte

    short Shortint Integer

    long Longfloat Float

    double Double

    boolean Booleanchar Character

    The classes in the table are calwrapper classes because objects of eaof these class types wrap a value of tcorresponding primitive type. Whenevevalue of one of the basic types appears an operand to + and the other operand isString object, the compiler arranges pass the value of the basic type as targument to the toString() method thatdefined in the corresponding wrapp

    String doubleString =Creates a String objefrom a value of any of t

  • 8/8/2019 Operations on Strings

    5/36

    Operations on Strings

    string1 ==Does not compare the strings themselvescompares the references to the strings, the result will be true only if string1 a

    Example II (2 Strings, Identical but Not the

    MatchStrings.java

    Comparing Strings for Equalty

    f (string1.equals(string3)) {

    System.out.println(string1.equals(stringis true. + so strings are equal.);Does a case-sensitive comparison corresponding characters in the strings areturns true if the strings are equal; faotherwise. Two strings are equal if they are tsame length, i.e., have the same number

  • 8/8/2019 Operations on Strings

    6/36

    This feature makes it possible

    to compare strings with the== operator effective.

    String interning ensures thatno 2 String objects

    equalsIgnoreCCheck for equality betweenstrin s, i norin the case

    Example III (String Identity)

    MatchStrings2.javaequalsDemo.jav

    aEqualsNotEqualT

    String Interning

  • 8/8/2019 Operations on Strings

    7/36

    encapsulate the same string,so all String objects

    encapsulate unique strings.This means that if 2 Stringvariables reference stringsthat are identical, thereferences must be identical,

    too.To arrange that all Stringobjects encapsulate uniquestrings, use intern().

    tring string1 = Too many ;tring string2 = cooks;tring string3 = Too many cooks;

    / Make string1 and string3 refer to separatetrings that are identical

    tring1 += string2;tring1 = string1.intern();// Intern string1

    Checks the string referenced string1 against all the Strobjects currently in existence. Ialready exists, the current objwill be discarded, and string1 wcontain a reference to the existiobject encapsulating the samstring. As a result, the expressi

  • 8/8/2019 Operations on Strings

    8/36

    All string constants andconstant String expressionsare automatically interned.

    Benefits of string interning:-(i) Reduces the amount of

    memory required forstoring String objects in

    the program. If theprogram generates a lot ofduplicate strings then thiswill be significant.

    Strin strin 4 = Too The reference stored string4 will be automaticathe same as the referen

    strin 1 = (strin 1 +interns the result of texpression (string1 string2), ensuring that t

  • 8/8/2019 Operations on Strings

    9/36

    (ii) Allows the use of ==instead of the equals()method when we want tocompare strings forequality. Since the ==operator just compares 2references, it will be much

    faster than the equals()method, which involves asequence of character-by-character comparisons.

    Checking the Start and End of a

    tring string1 = Too many cooks;f (string1.startsWith(Too)) {

    System.out.println(The string does startwith \Too\ too!);

    Tests whether string starts with particular charactsequence

  • 8/8/2019 Operations on Strings

    10/36

    string1.endsWith( Checks for whappears at the

    end of a strinSe uencin Strin s

    string1.compareTo(

    Compares 2 strings by comparing successicorresponding characters, starting with t1st character in each string. The procecontinues until either correspondicharacters are found to be different, or t

    last character in one or both strings reached. Characters are compared comparing their Unicode representations2 characters are equal if the numeric valuof their Unicode representations are equOne character is greater than another if t

    SequenceStrings.javaSortString.java

    Example IV (Ordering

    Value

    Meaning

    < 0 Invoking string 0 Invoking string

    int Case difference

  • 8/8/2019 Operations on Strings

    11/36

    Extractin Strin

    char charAt(int

    StringCharacters.java

    Example

    V (Getting at Characters in a

    Searchin Strin s or

    int index = 0;// Position of character in the

    string

    Returns -1 o

    search is

    index = Searches the string backwards, startwith the last character in the string. The variable index therefore contains tindex position of the last occurrence of a,

  • 8/8/2019 Operations on Strings

    12/36

    index = text.indexOf(a,Searches forwardsfrom a given positio

    nt aIndex = -1;// Position of 1st ant bIndex = -1;// Position of 1st b afte

    aIndex = text.indexOf(a);// Find firstaf (aIndex >= 0) {// Make sure you

    Finds the 1st

    that comes aft

    the 1st

    a in

    int aIndex = -1;// Search startpositionint count = 0; // Count of aoccurrences

    while ((aIndex = text.indexOf(a, +

    Used to count homany times articular charact

    Searchin or

  • 8/8/2019 Operations on Strings

    13/36

    Method Description

    indexOf(intch)

    Returns the indexposition of the 1st

    occurrence of thecharacter ch inthe String for

    which the methodis called. If thecharacter ch doesnot occur, -1 isreturned.

    indexOf(intch, intindex)

    Same as theprecedingmethod, but withthe searchstarting atposition index inthe string. If thevalue of index is

  • 8/8/2019 Operations on Strings

    14/36

    outside the legallimits for the

    String object, -1 isreturned.

    indexOf(String str)

    Returns the indexposition of the 1st

    occurrence of the

    substring str inthe String objectfor which themethod is called.If the substring

    str does notoccur, -1 isreturned.

    indexOf(String str, intindex)

    Same as theprecedingmethod, but withthe searchstarting at

  • 8/8/2019 Operations on Strings

    15/36

    position index inthe string. If the

    value of index isoutside the legallimits for theString object, -1 isreturned.

    String string1 = The Ides ofMarch; Returns

    FindCharacters.javaindexOfDemo.java

    Example

    VI (Exciting Concordance

  • 8/8/2019 Operations on Strings

    16/36

    Extractin

    String place = PalmSprings;

    The variable lastWord will contthe string Springs, whcorresponds to the substring startat index position 5 in place throughthe end of the string. Copies the substring from the origito form a new String object.

    Useful when a string has basically

  • 8/8/2019 Operations on Strings

    17/36

    String segment = Enables us to extract a substrifrom a string by specifying tindex positions of the 1st characin the substring and one beyo

    the last character of the substrias arguments to the method.

    ExtractSubstrings.java

    Example VII (Word for

  • 8/8/2019 Operations on Strings

    18/36

    Tokenizing a

    split Splits a string into tokens. Does this in a single step, returning the tokens from a string as an array

    tring text = to be or not to be, that is the

    uestion.;

    Specifies a patternfor a delimiter. Anydelimiter that matchesthe pattern is assumed

    to be a separator for a

    An integer value that is a count of tmaximum no. of times the pattern can applied to find tokens and, therefore, affethe maximum no. of tokens that can

    found. If 0, the pattern will be applied as matimes as possible, and any trailing emp

    tring[ ] words = text.split([, .]);//

    2nd argument

    Example VIII (Using a Tokenizer)

  • 8/8/2019 Operations on Strings

    19/36

    StringTokenizin

    g.java

    Modifying Versions of String

    String newText = text.replace( , /);//Replaces each spain the string te

    String sample = This isa string ;

    Removes whitespace frothe beginning and end ostring (but not the interior

    Creating Character Arrays from String Objec

    tring text = To be or not to be;

    har[ ] textArray = text.toCharArray();//

    String text = To be ornot to be;char[ ] textArray = new

    Copies characters from text at indpositions 9 to 11 inclusive, textArray[0] will be n, textArray[

  • 8/8/2019 Operations on Strings

    20/36

    The indexposition ofthe 1st

    characterto beextracted

    The indexpositionfollowingthe lastcharacter tobeextracted

    Thename ofthe arrayto holdthecharacte

    Theindex ofthearrayelementto hold

    Using the Collection-BasedforLoop with atring phrase = The quick brown fox

    umped over the lazy dog.;nt vowels = 0;

    or (char ch : phrase.toCharArray()) {ch = Character.toLowerCase(ch);if (ch == a || ch == e || ch == i || ch

    == o || ch == u) {++vowels;

    }

    Cant use a String object direcas the source of values forcollection-based for loop.

    getCharsDemo.javaTestGetChars.

    java

    Example IX (Using getChars())

  • 8/8/2019 Operations on Strings

    21/36

    Obtaining the Characters in a String as an Array of

    String text = To be or not to be;// Definea string

    Creating String Objects from Character Arrahar[ ] textArray = {T, o, , b, e, , or, , n, o, t, , t, o, , b, e };tring text = String.copyValueOf(textArray)

    ChangeCase.java.java

    ExampleX (Changing

  • 8/8/2019 Operations on Strings

    22/36

    The object text

    references the string

    String text =String.copyValueOf(textArray, 9,3);

    Extracts 3 charactestarting wtextArray[9], so te

    String(byteasciiChars[ ]);String(byteasciiChars[ ], int startInde

    Creating String Objects from Byte Arrays

    SubStringCons.java

    Example XI (Using a byte

  • 8/8/2019 Operations on Strings

    23/36

    Mutable strings Strings thatcan be changed

    Immutable strings Stringsthat cant be changed

    String objects cannot bechanged.

    Mutable Strings

    Strin Conversion & toStrin

    public String

    ExampleXII (Using

    help.javahelp1.javatoStringDemo.java

    StringBuffer and StringBuildobjects should be used whwe are transforming strin

    frequently adding, deletinor replacing substrings instring. Operations will faster and easier usmutable objects. If we hamainly static strings that

    occasionally need

  • 8/8/2019 Operations on Strings

    24/36

    Use StringBuffer /StringBuilder

    Thread- Not Thread-

    CreatingStringBufferObjects

    StringBuffer aString = new

    tring phrase = Experience is what you gewhen youre expecting something else.;

    tringBuffer myString = null;myString = new StringBuffer(Many a mickmakes a muckle);

    Only the variable created that doesn

    A StringBuffer variable can initialized with an exist

    The Capacity of a StringBuffer

  • 8/8/2019 Operations on Strings

    25/36

    A StringBuffer objectcontains a block of memory

    called a buffer, which mayor may not contain a string,and if it does, the stringneed not occupy the entire

    buffer. Thus, the length ofa string in a StringBufferobject can be differentfrom the length of thebuffer that the object

    contains. The length of thebuffer is referred to as thecapacity of theStringBuffer object.

  • 8/8/2019 Operations on Strings

    26/36

    When a StringBuffer object iscreated from an existing

    string,capacity = string length

    + 16

    The capacity of a StringBufferobject is not fixed though. Itgrows automatically as we add

    Both the capacand the length ain units of Unico

    characters, twice as ma

  • 8/8/2019 Operations on Strings

    27/36

    to the string to accommodatea string of any length.

    StringBuffer newString = new Object created wthe capacity to st50 characters. If the capacity vais omitted, the obj

    int theCapacity = aString.lengt

    aString.ensureCapa Used to change the default capacity If the current capacity of the aStriobject is less than 40, this will increase tcapacity of aString by allocating a nlarger buffer, but not necessarily with

    capacity of 40. The capacity will be tlarger of either the value that we specify (

    Changing the String Length for a StringBuffer

    aString.setLen When the length for a StringBuffer objectincreased, characters are added to the exististring and the extra characters will conta\u0000.

    More commonly used to decrease the lengt

    aString.setLeng

  • 8/8/2019 Operations on Strings

    28/36

    setLength() does notaffect the capacity of theobject unless the length isset to be greater than the

    capacity. In this case thecapacity will be increasedto accommodate the newstring length to a valuethat is twice the original

    capacity plus 2 if thelength we set is less thanthis value. If we specify alength that is greater than

    twice the original capacityplus two, the new capacity

  • 8/8/2019 Operations on Strings

    29/36

    will be the same as thelength we set.

    The capacity will always beincreased automaticallywhenever necessary to

    accommodate the longerstring.

    //Assume, capacity of aString =66

    //Assume, capacity of aString =66

    Specifying a ve lengthrowsStringIndexOutOfBound

    Adding to a StringBuffer Object

    StringBuffer aString = new

    StringBuffer(A stitch in time);

    aString will conta

    A stitch in ti

  • 8/8/2019 Operations on Strings

    30/36

    append() returns a referenceto the extended StringBuffer

    object, so we could also assignit to another StringBufferobject.

    Multiple append() operationsin a single statement :-

    StringBuffer bString =Now both aStriand bString poto the sam

    tringBuffer proverb = new StringBuffer();/Capacity = 16

    roverb.append(Many).append(

    The . opera( membselection

    operator) usto execute particularmethod for

    Appending a

    StringBuffer buf = newStringBuffer(Hard );String aString = Waxworks;

  • 8/8/2019 Operations on Strings

    31/36

    Appending Basic

    StringBuffer buf = newStringBuffer(The number is );long number = 999;

    buf.append(12.34); // buf contains The

    har[ ] text = { i, s, , e, x, a, c, t,, y};

  • 8/8/2019 Operations on Strings

    32/36

    Data types that can be appended

    to a StringBuffer objectboolean

    int long String Object

    char byte short float double

    Finding the Position of a Substring

    StringBuffer phrase = new StringBuffer(ontwo three four);

    position =This statement starts the searchindex position 6 so the first characters (index values 0 to 5)

    Replacing a Substring in the

    tringBuffer phrase = new StringBuffer(onwo three four);tring substring = two;tring replacement = twenty;

    nt position = phrase.lastIndexOf(substring)

    Becausereplacemeis a strcontaining

    morecharactersthansubstring, tlength of tstring inphrase will

    increased, a

  • 8/8/2019 Operations on Strings

    33/36

    Data types that can be used ininsert as a 2nd argumentboolean

    int long String Object

    char byte short float double

    startindex inthe

    Index position onebeyond the endindex of the

    stringto

    Inserting

    / Assume bufcontains the string Manyands make light work,

    insert(int index, char[ ] str, intInserts a substring into tStringBuffer object starting position index. The substringthe String representation length characters from t

  • 8/8/2019 Operations on Strings

    34/36

    Extracting Characters from a Mutable Strin

    charAt()

    Other Mutable String

    buf.setCharAt(Sets the 4th character in the

    tringBuffer phrase = newtringBuffer(When the boats come in);

    phrase.deleteDeletes the substring the from

    phrase, so it will then contain the stri

    tringBuffer palindrome = newtringBuffer(so many dynamos);

    Creating a StringObject from a StringBuffer

  • 8/8/2019 Operations on Strings

    35/36

    toString() is used extensivelyby the compiler together with

    append() to implement theconcatenation of Stringobjects.

    Implementedby the compileras

    tringBuffer proverb = newtringBuffer(Many hands make light work

    tring saying = Many + hands +

    tring saying = newtringBuffer().append(Many).append(

    Example - 13

  • 8/8/2019 Operations on Strings

    36/36

    UseStringBuffer.java