You are on page 1of 33

Operations on Strings

Joining Strings

String myString = “The quick brown fox” + “ jumps over the


lazy dog”;
String date = “31st “;
String month = “December”;
String lastDay = date + month; // Result is “31st December”

String phrase = “Too many”;


phrase += “ cooks spoil the broth”;
concat( Concatenates 2 strings

Example – I (String
Concatenation)
JoinStrings.java
TestConcat.jav
a
 The conversion of values of the basic
types to type String is actually
accomplished by using a static method,
toString(), of a standard class that
corresponds to the basic type (wrapper
class).
Basic The
Typeclasses
Wrapper Class
in the table are called wrapper classes
bytebecause objectsByteof each of these class types “ wrap” a value
shortof the corresponding
Short primitive type. Whenever a value of
one of the basic types appears as an operand to + and the
intother operandInteger
is a String object, the compiler arranges to
longpass the value Longof the basic type as the argument to the
float Float that is defined in the corresponding
toString() method
doublewrapper class.
DoubleThe toString() method returns the String
equivalent ofBoolean
boolean the value. All of this happens automatically
when you are concatenating strings using the + operator.
char Character

String doubleString =Creates a String object from a value


String.valueOf(3.14159);
of any of the basic types.
Operations on Strings
Does not compare the strings themselves; it compares the
string1 == tostring2
references the strings, so the result will be true only if string1
and string2 both refer to one and the same string.

Example – II (2 Strings, Identical but Not the


Same)
MatchStrings.jav
a

Comparing Strings for Equalty


if (string1.equals(string3)) {
System.out.println(“string1.equals(string3) is true.” + “ so
strings are equal.”);
}
Does a case-sensitive comparison of corresponding characters in the
strings and returns true if the strings are equal; false otherwise. Two
strings are equal if they are the same length, i.e., have the same
number of characters, and each character in one string is identical to
the corresponding character in the other.
Check for equality between 2 strings,
equalsIgnoreCase()
ignoring the case of the string characters

Example – III (String Identity)


MatchStrings2.java
equalsDemo.java
EqualsNotEqualTo.jav
a

String Interning
 This feature makes it possible to compare
strings with the == operator effective.
 String interning ensures that no 2 String
objects encapsulate the same string, so all
String objects encapsulate unique strings.
This means that if 2 String variables
reference strings that are identical, the
references must be identical, too.
To arrange that all String objects
encapsulate unique strings, use intern().

String string1 = “Too many “;


String string2 = “cooks”;
String string3 = “Too many cooks”;
// Make string1 and string3 refer to separate strings that are
identical Checks the string referenced by string1 against
string1 += string2; all the String objects currently in existence. If it
string1 = string1.intern();already
// Internexists, the current object will be
string1
discarded, and string1 will contain a reference to
the existing object encapsulating the same string.
As a result, the expression string1 == string3 will
evaluate to true, whereas without the call to
intern() it evaluated to false.

 All string constants and constant String


expressions are automatically interned.
The reference stored in string4 will be
String string4 = “Too “ +”many “;
automatically the same as the reference
stored in string1.
interns the result of the expression
string1 = (string1 + string2).intern();
(string1 + string2), ensuring that the
reference stored in string1 will be unique.

 Benefits of string interning :-


(i) Reduces the amount of memory
required for storing String objects in
the program. If the program
generates a lot of duplicate strings
then this will be significant.

(ii) Allows the use of == instead of the


equals() method when we want to
compare strings for equality. Since
the == operator just compares 2
references, it will be much faster than
the equals() method, which involves a
sequence of character-by-character
comparisons.

Checking the Start and End of a


 Tests whether a string starts
with a particular character
String string1 = “Too many cooks”; sequence
if (string1.startsWith(“Too”)) {  Case-sensitive
System.out.println(“The string does start with \”Too\” too!”);
}

Checks for what appears



string1.endsWith(“cooks”) at the end of a string
 Case-sensitive

Sequencing
Compares 2 strings by Strings
comparing successive corresponding
characters, starting with the 1st character in each string. The
process continues until either corresponding characters are
string1.compareTo(string2)
found to be different, or the last character in one or both
strings is reached. Characters are compared by comparing
ValueUnicode representations—so
their Meaning 2 characters are equal if
< 0numeric
the Invoking
valuesstring < strUnicode representations are equal.
of their
> 0 character
One Invokingis string
greater>str
than another if the numerical value of
its 0Unicode
The 2representation
strings are equalis greater than that of the other. A
character is less than another if its Unicode code is less than
that of the other.

int compareToIgnoreCase(StringCase
str) differences ignored
Example – IV (Ordering
Strings)
SequenceStrings.java
SortString.java

Extracting String

char charAt(int index)

Example – V (Getting at Characters in a


String)
StringCharacters.jav
a

Searching Strings for


int index = 0; // Position of character in the stringReturns -1 of search
index = text.indexOf(‘a’); // Find 1st index positionis containing
unsuccessful.
‘a’
 Searches the string backwards, starting with the last character
index
in the= string.
text.lastIndexOf(‘a’);
 The variable index therefore contains the index position of the
last occurrence of ‘a’, or -1 if it is not found.

Searches forwards from a


index = text.indexOf(‘a’, startIndex );
given position, startIndex

int aIndex = -1; // Position of 1st ‘a’ Finds the 1st ‘b’ that
int bIndex = -1; // Position of 1st ‘b’ comes
after ‘a’after the 1st ‘a’ in a
aIndex = text.indexOf(‘a’); // Find first ‘a’
string
if (aIndex >= 0) { // Make sure you found ‘a’
bIndex = text.indexOf(‘b’, ++aIndex); // Find 1st ‘b’
after 1st ‘a’
} int aIndex = -1; // Search start position
int count = 0; // Count of ‘a’ Used to count how many
occurrences
times a particular character
while ((aIndex = text.indexOf(‘a’, ++aIndex))
occurred in a string.
> -1) {
++count;
}
Searching for

Method Description
indexOf(int ch) Returns the index
position of the 1st
occurrence of the
character ch in the String
for which the method is
called. If the character ch
does not occur, -1 is
returned.
indexOf(int ch, Same as the preceding
int index) method, but with the
search starting at position
index in the string. If the
value of index is outside
the legal limits for the
String object, -1 is
returned.
indexOf(String Returns the index
str) position of the 1st
occurrence of the
substring str in the String
object for which the
method is called. If the
substring str does not
occur, -1 is returned.
indexOf(String Same as the preceding
str, int index) method, but with the
search starting at position
index in the string. If the
value of index is outside
the legal limits for the
String object, -1 is
returned.
String string1 = “The Ides of March”;
System.out.println(string1.startsWith(“Ides”, 4));
Returns true

Example – VI (Exciting Concordance


Entries)
FindCharacters.java
indexOfDemo.java
Extracting
 The variable lastWord will contain the string “Springs”,
String place = “Palm
which Springs”;
corresponds to the substring starting at index
String lastWord
position=5 place.substring(5);
in place through to the end of the string.
 Copies the substring from the original to form a new
String object.
 Useful when a string has basically 2 constituent
substrings.

 Enables
String segment = place.substring(7, 11); fromsta string by
us to extract a substring
specifying the index positions of the 1 character
in the substring and one beyond the last
character of the substring as arguments to the
method.
 The variable segment is set to the string “ring”:
Example – VII (Word for
Word)
ExtractSubstrings.jav
a

Tokenizing a
String
 Splits a string into tokens.
split()
 Does this in a single step, returning all the tokens from a
; string as an array of String objects.

String text = “to be or not to be, that is the question.”;


String[ ] words = text.split(“[, .]”, 0); // Delimiters are comma,
space, or period
 Specifies
 An integer valuea that
pattern
is a countfor of athe maximum no. of times the
delimiter.
pattern can beAny
applieddelimiter that and, therefore, affects the
to find tokens
matches
maximum no.the
of pattern is assumed
tokens that can be found.
 If 0,tothe
be pattern
a separator for applied
will be a token.as many times as possible, and
any trailing empty tokens will be discarded.
 If -1, the pattern will also be applied as many times as possible,
but trailing empty tokens will be retained and returned.

String[ ] words = text.split(“[, .]”); // Delimiters are comma,


space, or period
2nd argument defaults to 0

Example – VIII (Using a Tokenizer)


)
StringTokenizing.jav
a

Modifying Versions of String


Objects
String newText = text.replace(‘ ‘, ‘/’); //Replaces
Modify each space in the
the string text
string text with a slash (/)

String sample = “ This is a string


Removes “; from the
whitespace
beginning and end of a string (but not
String result = sample.trim();
the interior)

Creating Character Arrays from String Objects


String text = “To be or not to be”;
char[ ] textArray = text.toCharArray(); // Create the array from
the string
String text = “To
Copies be or from
characters not to textbe”;
at index positions 9 to 11
inclusive, so textArray[0] will be ‘n’, textArray[1] will be ‘o’,
char[ ] textArray = new char[3];
and textArray[2] will be ‘t’.
text.getChars(9, 12, textArray, 0);

The index The index The name The index


position of the position following of the array of the
1st character to the last to hold the array
be extracted character to be characters element to
from the string extracted from extracted hold the 1st
(type int) the string (type (type character
int) char[ ]) (type int)
Example – IX (Using getChars())
)
getCharsDemo.jav
a
TestGetChars.java

Using the Collection-Based for Loop with a


String
String phrase = “The quick brown fox jumped over the lazy
dog.”; Can’t use a String object directly as the
int vowels = 0; source of values for a collection-based for
loop.
for (char ch : phrase.toCharArray()) {
ch = Character.toLowerCase(ch);
if (ch == ‘a’ || ch == ‘e’ || ch == ‘i’ || ch == ‘o’ || ch == ‘u’) {
++vowels;
}
}
System.out.println(“The phrase contains “ + vowels + “
Example – X (Changing
Case)
ChangeCase.java.jav
a

Obtaining the Characters in a String as an Array of


Bytes
String text = “To be or not to be”; // Define a string
byte[ ] textArray = text.getBytes(); // Get equivalent byte array

Creating String Objects from Character Arrays


char[ ] textArray = {‘T’, ‘o’, ‘ ‘, ‘b’, ‘e’, ‘ ‘, ‘o’, ‘r’, ‘ ‘, ‘n’, ‘o’, ‘t’, ‘ ‘,
‘t’, ‘o’, ‘ ‘, ‘b’, ‘e’ };
String text = String.copyValueOf(textArray); The object text references the
string “To be or not to be”.

String text = new String(textArray);


String text = String.copyValueOf(textArray, 9, 3);with
Extracts 3 characters starting
textArray[9], so text will contain the
string “not”
String text = new String(textArray, 9, 3);
Creating String Objects from Byte Arrays

String(byte asciiChars[ ]);


String(byte asciiChars[ ], int startIndex, int numChars);

Example – XI (Using a byte


array)
SubStringCons.java

String Conversion & toString()

public String toString()

Example – XII (Using


help.java toString())
help1.java
toStringDemo.java
Mutable Strings
 Mutable strings  Strings thatand
StringBuffer can StringBuilder
be objects
changed should be used when we are
transforming strings frequently— adding,
 Immutable strings  Strings that can’t be
deleting, or replacing substrings in a
changed string. Operations will be faster and
 String objects cannot be using
easier changed.
mutable objects. If we have
mainly static strings that we occasionally
 Use StringBuffer / StringBuilder
need to concatenate in your application,
Thread-safe then String objects will be the best
Not Thread-safe
choice.

Creating StringBuffer Objects

StringBuffer aString = new StringBuffer(“A stitch in time”);


String phrase = “Experience is what you get when you’re
expecting something else.”;
StringBuffer buffer = new StringBuffer(phrase);
StringBuffer myString = null;
Only the variable created that doesn’t refer to anything

myString = new StringBuffer(“Many a mickle makes a


muckle”); A StringBuffer variable can be initialized with an
existing StringBuffer object
StringBuffer aString = myString;

The Capacity of a StringBuffer


Object
 A StringBuffer object contains a block
of memory called a buffer, which may
or may not contain a string, and if it
does, the string need not occupy the
entire buffer. Thus, the length of a
string in a StringBuffer object can be
different from the length of the buffer
that the object contains. The length of
the buffer is referred to as the
capacity of the StringBuffer object.

Both the capacity and the


 When a StringBuffer object is created fromin units of
length are
an existing string, Unicode characters, so
capacity = string length +twice
16 as many bytes will
be occupied in memory.

 The capacity of a StringBuffer object is not


fixed though. It grows automatically as we
add to the string to accommodate a string
of any length.
StringBuffer newString = newcreated
 Object StringBuffer(50);
with the capacity
to store 50 characters.
 If the capacity value is omitted,
the object would have a default
capacity of 16 characters.

int theCapacity = aString.capacity();aString.length() + 16


aString.ensureCapacity(40);
 Used to change the default capacity
 If the current capacity of the aString object is less than 40, this
will increase the capacity of aString by allocating a new larger
buffer, but not necessarily with a capacity of 40. The capacity
will be the larger of either the value that we specify (40 in this
case), or twice the current capacity + 2 (i.e., 66), given that
aString is defined as before.

Changing the String Length for a StringBuffer


Object
 When aString.setLength(8);
the length for a StringBuffer object is increased, characters
are added to the existing string and the extra characters will
contain ‘\u0000’.
aString.setLength(16);
 More commonly used to decrease the length, in which case the
string is truncated.
 setLength() does not affect the
capacity of the object unless the
length is set to be greater than the
capacity. In this case the capacity
will be increased to accommodate
the new string length to a value that
is twice the original capacity plus 2 if
the length we set is less than this
value. If we specify a length that is
greater than twice the original
capacity plus two, the new capacity
will be the same as the length we
set.
//Assume, capacity of aString = 66
aString.setLength(100); //capacity
Specifying a –ve set to 134
length throws
StringIndexOutOfBoundsException
//Assume, capacity of aString = 66
exception.
aString.setLength(150); //capacity set to 150
Adding to a StringBuffer Object

StringBuffer aString = new StringBuffer(“A stitch


aString will in time”);
contain
aString.append(“ saves nine”); “A stitch in time saves nine”.

 The capacity will always be increased


automatically whenever necessary to
accommodate the longer string.
 append() returns a reference to the
extended StringBuffer object, so we could
also assign it to another StringBuffer
object.
Now both aString and
StringBuffer bString = aString.append(“ saves
bString point to thenine”);
same
StringBuffer object.

 Multiple append() operations in a single


The ‘.’ operator
( member selection
statement :- operator) used to
StringBuffer proverb = new StringBuffer(); // Capacity
execute= a16particular
method for an object
proverb.append(“Many”).append(“ hands”).append(“ has make”). left-to-right
append(“ light”).append(“
associativity.
Appending a
Substring
StringBuffer buf = new StringBuffer(“Hard “);
String aString = “Waxworks”;
buf.append(aString, 3, 4);

Appending Basic
Types
StringBuffer buf = new StringBuffer(“The number is “);
long number = 999;
buf.append(number); // buf contains ‘The number is 999’

buf.append(12.34); // buf contains ‘The number is 99912.34’

char[ ] text = { ‘i’, ‘s’, ‘ ‘, ‘e’, ‘x’, ‘a’, ‘c’, ‘t’, ‘l’, ‘y’};
buf.append(text, 2, 8); // buf contains “The number is 99912.34
exactly”.
Data types that can be appended to a
StringBuffer object
boolean int long String Object
char byte short float double

Finding the Position of a Substring

StringBuffer phrase = new StringBuffer(“one two three four”);


int position = phrase.lastIndexOf(“three”); // Returns 8
This statement starts the search at index position
6 so the first 6 characters (index values 0 to 5) in
the buffer will not be examined.
position = phrase.lastIndexOf(“three”, 6);

Replacing a Substring in the


Because
Buffer replacement is a
StringBuffer phrase = new StringBuffer(“one twostringthree four”);
containing
String substring = “two”; more characters
than substring, the
String replacement = “twenty”; length of the string
int position = phrase.lastIndexOf(substring); // Find
in start of
“two” phrase will be
increased, and the
phrase.replace(position, position+substring.length(),
start index new contents
stringwill
to be
be
Index position one beyond
in the “one twenty three
the end index ofinserted the
buffer four”.
substring to be replaced

Inserting
Strings
// Assume buf contains the string “Many hands make light work”,
buf.insert(4, “ old”); // buf will contain the string “Many old hands
make light work” nd
Data types that can be used in insert as a 2
argument
boolean int long String Object
char byte short float double
Inserts a substring into the StringBuffer
insert(int index, char[
object] str , int offset
starting , int length
at position ) The
index.
substring is the String representation of
length characters from the str[ ] array,
starting at position offset.

Extracting Characters from a Mutable String


charAt()
getChars()

Other Mutable String


Operations
buf.setCharAt(3, ‘Z’);
Sets the 4th character in the string to ‘Z’.

StringBuffer phrase = new StringBuffer(“When the boats come


in”);
phrase.deleteCharAt(10); // phrase will contain the string
Deletes the substring “the “ from phrase, so it will then
phrase.delete(5, 9);
contain the string “When bats come in”.

StringBuffer palindrome = new StringBuffer(“so many


dynamos”);
palindrome.reverse(); // palindrome containing the useful
Creating a String Object from a StringBuffer
Object
StringBuffer proverb = new StringBuffer(“Many hands make
light work”);
String saying = proverb.toString();
 toString() is used extensively by the
compiler together with append() to
implement the concatenation of String
objects.
String saying = “Many” + “ hands” + “ make” + “ light” + “ work”;
Implemented by the
compiler as

String saying = new StringBuffer().append(“Many”).append(“


hands”).
append(“ make”).append(“ light”).append(“
Example - 13

UseStringBuffer.java

You might also like