0% found this document useful (0 votes)
5 views8 pages

Notes 24CS202 OOP Through Java Unit II Chapter 2 String Handling

Uploaded by

chundurumanas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views8 pages

Notes 24CS202 OOP Through Java Unit II Chapter 2 String Handling

Uploaded by

chundurumanas
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

24CS202 – OOP Through Java

UNIT- II

Chapter 2: String Handling


Strings, which are widely used in Java programming, are a sequence of characters. In the
Java programming language, strings are objects. The Java platform provides the String class to
create and manipulate strings.

1.1 Creating Strings

The most direct way to create a string is to write:

String greeting = "Hello world!";

In this case, "Hello world!" is a string literal—a series of characters in your code that is
enclosed in double quotes. Whenever it encounters a string literal in your code, the compiler
creates a String object with its value—in this case, Hello world!

As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has thirteen constructors that allow you to provide the initial value of
the string using different sources, such as an array of characters:

char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.' };


String helloString = new String(helloArray);
[Link](helloString);

The last line of this code snippet displays hello.

The String class is immutable; so that once it is created a String object cannot be
changed. The String class has a number of methods, some of which will be discussed below, that
appear to modify strings. Since strings are immutable, what these methods really do is create and
return a new string that contains the result of the operation.

String Length

Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number of
characters contained in the string object. After the following two lines of code have been
executed, len equals 17:
[Link] Virapratap
1
Asst. Professor
CSE Dept, V.R.S.E.C
String palindrome = "Dot saw I was Tod";
int len = [Link]();

Concatenating Strings

The String class includes a method for concatenating two strings:


[Link](string2);

This returns a new string that is string1 with string2 added to it at the end.

You can also use the concat() method with string literals, as in:
"My name is ".concat("Rumplestiltskin");

Strings are more commonly concatenated with the + operator, as in


"Hello," + " world" + "!"

which results in
"Hello, world!"

The + operator is widely used in print statements. For example:


String string1 = "saw I was ";
[Link]("Dot " + string1 + "Tod");

Which prints

Dot saw I was Tod

Such a concatenation can be a mixture of any objects. For each object that is not a String,
its toString() method is called to convert it to a String.

Manipulating Characters in a String

The String class has a number of methods for examining the contents of strings, finding
characters or substrings within a string, changing case, and other tasks.

Getting Characters and Substrings by Index

You can get the character at a particular index within a string by invoking the charAt() accessor
method. The index of the first character is 0, while the index of the last character is length()-1.
For example, the following code gets the character at index 9 in a string:
String anotherPalindrome = "Niagara. O roar again!";
char aChar = [Link](9);

[Link] Virapratap
2
Asst. Professor
CSE Dept, V.R.S.E.C
Indices begin at 0, so the character at index 9 is 'O', as illustrated in the following figure:

If you want to get more than one consecutive character from a string, you can use
the substring method. The substring method has two versions, as shown in the following table:
The substring Methods in the String Class
Method Description
Returns a new string that is a substring of this string.
String substring(int beginIndex, int The first integer argument specifies the index of the
endIndex) first character. The second integer argument is the
index of the last character - 1.
Returns a new string that is a substring of this string.
The integer argument specifies the index of the first
String substring(int beginIndex)
character. Here, the returned substring extends to the
end of the original string.

The following code gets from the Niagara palindrome the substring that extends from
index 11 up to, but not including, index 15, which is the word "roar":

String anotherPalindrome = "Niagara. O roar again!";


String roar = [Link](11, 15);

Other Methods for Manipulating Strings

Here are several other String methods for manipulating strings:

Other Methods in the String Class for Manipulating Strings


Method Description
Searches for a match as specified by the string
String[] split(String regex) argument (which contains a regular
String[] split(String regex, int limit) expression) and splits this string into an array
of strings accordingly. The optional integer

[Link] Virapratap
3
Asst. Professor
CSE Dept, V.R.S.E.C
argument specifies the maximum size of the
returned array. Regular expressions are
covered in the lesson titled "Regular
Expressions."
CharSequence subSequence(int beginIndex, Returns a new character sequence constructed
int endIndex) from beginIndex index up untilendIndex - 1.
Returns a copy of this string with leading and
String trim()
trailing white space removed.
Returns a copy of this string converted to
String toLowerCase() lowercase or uppercase. If no conversions are
String toUpperCase() necessary, these methods return the original
string.

Searching for Characters and Substrings in a String

Here are some other String methods for finding characters or substrings within a string.
The String class provides accessor methods that return the position within the string of a specific
character or substring: indexOf() and lastIndexOf(). The indexOf() methods search forward from
the beginning of the string, and the lastIndexOf()methods search backward from the end of the
string. If a character or substring is not found, indexOf() and lastIndexOf() return -1.

The String class also provides a search method, contains, that returns true if the string
contains a particular character sequence. Use this method when you only need to know that the
string contains a character sequence, but the precise location isn't important.

The following table describes the various string search methods.

The Search Methods in the String Class


Method Description
int indexOf(int ch) Returns the index of the first (last) occurrence
int lastIndexOf(int ch) of the specified character.
Returns the index of the first (last) occurrence
int indexOf(int ch, int fromIndex)
of the specified character, searching forward
int lastIndexOf(int ch, int fromIndex)
(backward) from the specified index.
int indexOf(String str) Returns the index of the first (last) occurrence
int lastIndexOf(String str) of the specified substring.

[Link] Virapratap
4
Asst. Professor
CSE Dept, V.R.S.E.C
Returns the index of the first (last) occurrence
int indexOf(String str, int fromIndex)
of the specified substring, searching forward
int lastIndexOf(String str, int fromIndex)
(backward) from the specified index.
Returns true if the string contains the specified
boolean contains(CharSequence s)
character sequence.

CharSequence is an interface that is implemented by the String class. Therefore, you can
use a string as an argument for the contains() method.

Replacing Characters and Substrings into a String

The String class has very few methods for inserting characters or substrings into a string. In
general, they are not needed: You can create a new string by concatenation of substrings you
have removed from a string with the substring that you want to insert.

The String class does have four methods for replacing found characters or substrings, however.
They are:

Methods in the String Class for Manipulating Strings


Method Description
Returns a new string resulting from replacing
String replace(char oldChar, char newChar) all occurrences of oldChar in this string with
newChar.
Replaces each substring of this string that
String replace(CharSequence target,
matches the literal target sequence with the
CharSequence replacement)
specified literal replacement sequence.
Replaces each substring of this string that
String replaceAll(String regex, String
matches the given regular expression with the
replacement)
given replacement.
Replaces the first substring of this string that
String replaceFirst(String regex, String
matches the given regular expression with the
replacement)
given replacement.

1.2 String Buffer

A string buffer implements a mutable sequence of characters. A string buffer is like


a String, but can be modified. At any point in time it contains some particular sequence of

[Link] Virapratap
5
Asst. Professor
CSE Dept, V.R.S.E.C
characters, but the length and content of the sequence can be changed through certain method
calls.

String buffers are safe for use by multiple threads. The methods are synchronized where
necessary so that all the operations on any particular instance behave as if they occur in some
serial order that is consistent with the order of the method calls made by each of the individual
threads involved.

String buffers are used by the compiler to implement the binary string concatenation
operator +. For example, the code:

x = "a" + 4 + "c"

is compiled to the equivalent of:

x = new StringBuffer().append("a").append(4).append("c")
.toString()

which creates a new string buffer (initially empty), appends the string representation of
each operand to the string buffer in turn, and then converts the contents of the string buffer to a
string. Overall, this avoids creating many temporary strings.

The principal operations on a StringBuffer are the append and insert methods, which are
overloaded so as to accept data of any type. Each effectively converts a given datum to a string
and then appends or inserts the characters of that string to the string buffer. The append method
always adds these characters at the end of the buffer; the insert method adds the characters at a
specified point.

For example, if z refers to a string buffer object whose current contents are "start", then
the method call [Link]("le") would cause the string buffer to contain "startle",
whereas [Link](4, "le") would alter the string buffer to contain "starlet".

In general, if sb refers to an instance of a StringBuffer, then [Link](x) has the same


effect as [Link]([Link](), x).

Every string buffer has a capacity. As long as the length of the character sequence
contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new
internal buffer array. If the internal buffer overflows, it is automatically made larger.

Method Summary
StringBuffer append(String str)
Appends the string to this string buffer.
StringBuffer append(StringBuffer sb)
Appends the specified StringBuffer to this StringBuffer.

[Link] Virapratap
6
Asst. Professor
CSE Dept, V.R.S.E.C
int capacity()
Returns the current capacity of the String buffer.
char charAt(int index)
The specified character of the sequence currently represented by the
string buffer, as indicated by the index argument, is returned.
StringBuffer delete(int start, int end)
Removes the characters in a substring of this StringBuffer.
StringBuffer deleteCharAt(int index)
Removes the character at the specified position in
this StringBuffer (shortening the StringBuffer by one character).
int indexOf(String str)
Returns the index within this string of the first occurrence of the
specified substring.
StringBuffer insert(int offset, String str)
Inserts the string into this string buffer.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the
specified substring.
int length()
Returns the length (character count) of this string buffer.
StringBuffer replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with
characters in the specified String.
StringBuffer reverse()
The character sequence contained in this string buffer is replaced by the
reverse of the sequence.
void setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch.
void setLength(int newLength)
Sets the length of this String buffer.
CharSequence subSequence(int start, int end)
Returns a new character sequence that is a subsequence of this
sequence.
String substring(int start)
Returns a new String that contains a subsequence of characters currently
contained in this [Link] substring begins at the specified index and
extends to the end of theStringBuffer.

[Link] Virapratap
7
Asst. Professor
CSE Dept, V.R.S.E.C
String substring(int start, int end)
Returns a new String that contains a subsequence of characters currently
contained in this StringBuffer.
String toString()
Converts to a string representing the data in this string buffer.
1.3 String Tokenizer

The [Link] class allows you to break a string into tokens. It is


simple way to break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description
StringTokenizer(String str) creates StringTokenizer with specified string.
StringTokenizer(String str, creates StringTokenizer with specified string and delimeter.
String delim)
StringTokenizer(String str, creates StringTokenizer with specified string, delimeter and
String delim, boolean returnValue. If return value is true, delimiter characters are
returnValue) considered to be tokens. If it is false, delimiter characters serve
to separate tokens.

Methods of StringTokenizer class

The 6 useful methods of StringTokenizer class are as follows:

Public method Description


boolean hasMoreTokens() checks if there is more tokens available.
String nextToken() returns the next token from the StringTokenizer object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.

[Link] Virapratap
8
Asst. Professor
CSE Dept, V.R.S.E.C

You might also like