0% found this document useful (0 votes)
14 views

String Handling Module 3

String Handling Module 3

Uploaded by

Alvas CSE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

String Handling Module 3

String Handling Module 3

Uploaded by

Alvas CSE
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

String Handling

Module 3
Contents
• The String Constructors,
• Special String Operations,
• Character Extraction,
• String Comparison,
• Searching Strings,
• Modifying a String,
• Data Conversion Using valueOf(),
• String Buffer,
• String Builder
What is String ?
• Strings, which are widely used in Java programming, are a sequence of
characters.
• In Java programming language, strings are treated as objects.
• The java.lang.String class is used to create string object.
• The Java platform provides the String class to create and manipulate
strings.
String – Object or Primitive?
• Strings could be considered a primitive type in Java, but in fact they
are not.
• A String is actually made up of an array of char primitives.
What is String ?
String objects are immutable!
• That means once a string object is created it cannot be altered.
• For mutable string, you can use StringBuffer and StringBuilder
classes.

[An object whose state cannot be changed after it is created is


known as an Immutable object.
String, Integer, Byte, Short, Float, Double and all other wrapper
class's objects are immutable.]
How to create String object?
There are two ways to create String object:
1. By string literal
For Example:
String s="welcome";

2. By new keyword
For Example:
String s=new String("Welcome");
Java String Example

Output :
java
strings
example
The String Constructors
The String Constructors
• The String class supports several constructors. To create an empty String, call
the default constructor. For example,
String s = new String();
• will create an instance of String with no characters in it.
• 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:
The String Constructors
• You can specify a subrange of a character array as an initializer
using the following constructor:
String(char chars[ ], int startIndex, int numChars)
• Here, startIndex specifies the index at which the subrange begins,
and
• numChars specifies the number of characters to use.
• Here is an example:
The String Constructors
• You can construct a String object that contains the same character sequence as another
String object using this constructor:

String(String strObj)
• Here, strObj is a String object.
• Consider this example:
The String Constructors
• Even though Java’s char type uses 16 bits to represent the basic Unicode
character set, the typical format for strings on the Internet uses arrays of 8-bit
bytes constructed from the ASCII character set.
• Because 8-bit ASCII strings are common, the String class provides
constructors that initialize a string when given a byte array. Two forms are
shown here:
String(byte chrs[ ])
String(byte chrs[ ], int startIndex, int numChars)
• In each of these constructors, the byte-to-character conversion is done by using
the default character encoding of the platform.
The String Constructors
• The following program illustrates these the byte-to-character conversion is
done by using the default character encoding of the platform for each
constructors :

This program generates the following output:


ABCDEF
CDE
String Length
• The length of a string is the number of characters that it contains.
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:
Special String Operations
String Literals
• We created a String instance from an array of characters by using the new
operator.
• However, there is an easier way to do this using a string literal.
• For each string literal in your program, Java automatically constructs a String
object. Thus, you can use a string literal to initialize a String object.
• For example, the following code fragment creates two equivalent strings:
String Concatenation
• There are 2 methods to concatenate two or more string.

Using Using +
concat() operator
method

Concatenates
two or more
string.
String Concatenation with Other Data Types
• You can concatenate strings with other types of data. For example,

• In this case, age is an int rather than another String, but the output produced is
"He is 9 years old.". This is because the int value in age is automatically
converted into its string representation within a String object.
• Be careful when you mix other types of operations with string concatenation
expressions, however. You might get surprising results. Consider the following:

Output -> four: 4


Output -> four: 22
String Conversion and toString( )
• One way to convert data into its string representation is by calling
one of the overloaded versions of the string conversion method
valueOf( ) defined by String.
• valueOf( ) is overloaded for all the primitive types and for type
Object.
• For the primitive types, valueOf( ) returns a string that contains
the human-readable equivalent of the value with which it is
called.
• For objects, valueOf( ) calls the toString( ) method on the object.
String Conversion and toString( )
Character Extraction
charAt( )
• To extract a single character from a String, you can refer directly to an
individual character via the charAt( ) method. It has this general form:
char charAt(int where)
• Here, 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( )
• If you need to extract more than one character at a time, you can use the
getChars( ) method. It has this general form:
void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

• Here, sourceStart specifies the index of the beginning of the substring, and
sourceEnd specifies an index that is one past the end of the desired substring.
getBytes( )
• There is an alternative to getChars( ) that stores the characters in
an array of bytes.
• This method is called getBytes( ), and it uses the default
character-to-byte conversions provided by the platform. Here is its
simplest form:
byte[ ] getBytes( )
• Other forms of getBytes( ) are also available. getBytes( ) is most
useful when you are exporting a String value into an environment
that does not support 16-bit Unicode characters.
toCharArray( )
• If you want to convert all the characters in a String object into a
character array, the easiest way is to call toCharArray( ).
• It returns an array of characters for the entire string. It has this
general form:
char[ ] toCharArray( )
• This function is provided as a convenience, since it is possible to
use getChars( ) to achieve the same result.
String Comparison
String Comparison
• String comparison can be done in 6 ways.

Using
By CompareTo()
equalsIgnoreCase( )
method
method

Using == operator By
regionMatches( )
method

Using equals() String By startsWith( )


and endsWith( )
method
Comparison methods
equals( ) and equalsIgnoreCase( )
• To compare two strings for equality, use equals( ). It has this general form:
boolean equals(Object str)
• Here, str is the String object being compared with the invoking String
object. It returns true if the strings contain the same characters in the same
order, and false otherwise. The comparison is case-sensitive.
• To perform a comparison that ignores case differences, call
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.
equals( ) and equalsIgnoreCase( )
• Here is an example that demonstrates equals( ) and equalsIgnoreCase( ):
regionMatches( )
• The regionMatches( ) method compares a specific region inside a string with
another specific region in another string.
• There is an overloaded form that allows you to ignore case in such
comparisons. Here are the general forms for these two methods:
startsWith( ) and endsWith( )
• String defines two methods that are, more or less, specialized forms of
regionMatches( ).
• The startsWith( ) method determines whether a given String begins with a
specified string. Conversely, endsWith( ) determines whether the String in
question ends with a specified string.
• They have the following general forms:
boolean startsWith(String str)
boolean endsWith(String str)
• Here, str is the String being tested. If the string matches, true is returned.
Otherwise, false is returned.
startsWith( ) and endsWith( )
• For example,

"Foobar".endsWith("bar")

"Foobar".startsWith("Foo")
• are both true.
• A second form of startsWith( ), shown here, lets you specify a starting point:

boolean startsWith(String str, int startIndex)


• Here, startIndex specifies the index into the invoking string at which point the search
will begin. For example,

"Foobar".startsWith("bar", 3)
• returns true.
equals( ) Versus ==
• It is important to understand that the equals( ) method and the == operator perform two
different operations.
• the equals( ) method compares the characters inside a String object.
• The == operator compares two object references to see whether they refer to the same
instance.
compareTo( )
• A string is less than another if it comes before the other in dictionary order. A
string is greater than another if it comes after the other in dictionary order.
• The method compareTo( ) serves this purpose.
• It is specified by the Comparable<T> interface, which String implements. It
has this general form:
int compareTo(String str)
• Here, str is the String being compared with the invoking String. The result of
the comparison is returned and is interpreted as shown here:
compareTo( )
• Here is a sample program that sorts an array of strings. The program uses
compareTo( ) to determine sort ordering for a bubble sort:

You might also like