Professional Documents
Culture Documents
i
Chapter 3
3.1 Introduction
• String is the array of character.
• We use them for printing messages for the user; for referring to files on disk or
other external media; and for peoples names, addresses, and affiliations.
• String is a defined type (class) in Javathat is, a string is an object and therefore
has methods. It is not an array of characters (though it contains one) and should
not be thought of as an array.
• If you need to change characters within a String , you should instead create a
StringBuilder (possibly initialized to the starting value of the String ), manipu-
late the StringBuilder to your hearts content, and then convert that to String at
the end, using the ubiquitous toString() method.
1
Solution:
3. Write program to create a two string object initialize it using any string constant
and print it.
Solution:
Methods Description
replace() replaces the specified old character with the specified new
character
2
Solution:String methods demo
3
Assignment
1. Write a Java program to compare two strings lexicographically. Two strings are
lexicographically equal if they are the same length and contain the same charac-
ters in the same positions.
Solution
2. Write a Java program to compare two strings lexicographically, ignoring case dif-
ferences.
Solution
3. Write a Java program to check whether a given string ends with the contents of
another string.
4
Solution
4. Write a Java program to test if a given string contains the specified sequence of
char values.
Solution
5. Write a Java program to get the index of all the characters of the alphabet. "The
quick brown fox jumps over the lazy dog."; String str = "The quick brown fox
jumps over the lazy dog.";
Solution
5
6. Write a program to enter a string and count the frequency each character present
in it.
Solution
class Main {
static void CountOccr ( String s )
{
int count []= new int [26];
// remove the spaces if any
s = s. replace ( " " , " ") ;
s =s. toLowerCase () ;
for ( int i =0; i < s . length () ; i ++)
{
char ch =s . charAt ( i ) ;
count [ch -97]++;
}
// print
for ( int i =0; i <26; i ++)
{
if ( count [ i ]!=0)
{
System . out . println ((( char ) ( i +97) ) + "
"+ count [ i ]) ;
}
}
}
public static void main ( String [] args ) {
String s= " java programs " ;
CountOccr (s) ;
}
}
• Note that the end index is one beyond the last character! Java adopts this half
open interval (or inclusive start, exclusive end) policy fairly consistently;
6
Assignment
1. Demonstrate how to use substring() and its variation, indexOf(), lastIndexOf(),
length() .
Solution:
3. Write a program to find sub string of a string from a start index to end index.
4. Write a program which read two string from user and concat the sub string from
0 to 5 index of first string with the 0 to 7 indexed of the second string and print
the resultant string.
Not: Your program must handle the any length string.
• A StringTokenizer normally breaks the String into tokens at what we would think
of as word boundaries in European languages.
Example:
• Sometimes you want to break at some other character. No problem. When you
construct your StringTokenizer, in addition to passing in the string to be tok-
enized, pass in a second string that lists the break characters. For example:
7
Example:
Assignment
1. Demonstrate the use of StringTokenizer class and its method hasMoreToken(),
nextToken()
Solution:
2. Write a program to read a string and tokenize the string for ’,’ or ’|’ token.
Solution:
8
4. Write a program which read a string and process it, if consecutive delimiter comes
ignore it else print the token.
Solution
9
Solution
5. Write a program using java to read a string and find number of words present in
that string.
6. Write a program to read a string whose words are separated by ’,’ find the num-
ber of words and number of ’,’ present in that string.
Solution
10
3.5 Putting Strings Together with StringBuilder
An object of one of the StringBuilder classes basically represents a collection of charac-
ters. It is similar to a String object, but, as mentioned, Strings are immutable. String-
Builders are mutable and designed for, well, building Strings.
3.5.1 Synchronization
Only one thread at a time is allowed to run the given method (or any other synchro-
nized method in the same class) in a given object instance (for static methods, only
one thread is allowed to run the method at a time). You can synchronize methods or
smaller blocks of code.
Problem: The add() method simply uses the current number of objects as an ar-
ray index then increments it.
1. Threads A and B both wish to call this method. Suppose that Thread A gets
interrupted after 1 but before 2, and then Thread B gets to run.
2. Thread B does , overwriting the contents of data[max] ; weve now lost all refer-
ence to the object that Thread A passed in!
3. Thread B then increments max at and returns. Later, Thread A gets to run again;
it resumes at and increments max past the last valid object. So not only have we
lost an object, but we have an uninitialized reference in the array.
11
Problem: // Build a StringBuilder and append some things to it.
2. Problem: StringBuilder delete(int start, int end): This method removes the
characters in a substring of this sequence.
Solution: delete() demo
class Main {
public static void main ( String [] args )
{
StringBuilder str = new StringBuilder ( " Rama Chandra " );
System . out . println ( " Original String = " + str ) ;
// remove the substring from index 7
StringBuilder afterRemoval = str . delete (7 ,8) ;
System . out . println ( afterRemoval ) ;
// remove the substring 7 -9
System . out . println ( str . delete (7 ,10) ) ;
}
}
Output :
Original String = Rama Chandra
Rama Chndra
Rama Cha
4. StringBuilder insert(): This method inserts the string representation of the char
argument into this sequence.
12
Solution: insert() demo
5. StringBuilder replace(int start, int end, String str): This method replaces
the characters in a substring of this sequence with characters in the specified
String.
class GFG {
public static void main ( String [] args )
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder str = new StringBuilder ( " Tony Stark
will die ");
// print string
System . out . println ( " String = " + str . toString () ) ;
// replace Character from index 15 to 16 by " not "
StringBuilder strReturn = str . replace (15 , 16 , "
not ") ;
// print string
System . out . println ( " After Replace () String = " +
strReturn . toString () ) ;
}
}
Solution:reverse() demo
13
Solution: Performance Comparision of StringBuilder and StringBuffer
Assignment
1. WAP to read a string from user and remove all delimeters from the string and
create an output string which consist of string without any delimeters of the in-
put string.
2. WAP to convert a list of items into a comma-separated list, while avoiding get-
ting an extra comma after the last element of the list.
Solution
14
3.6 Processing a String One Character at a Time
Problem
You want to process the contents of a string, one character at a time.
Solution
Use a for loop and the String’s charAt() method. Or a “for each” loop and the String’s
toCharArray() method.
Solution
3.6.1 Checksum
A “checksum” is a numeric quantity representing and confirming the contents of a file.
Assignment
1. Write a program which read a string from the user and find its checksum.
2. WAP to read a file using FileReader and BufferedReader and find the checksum.
BufferedReader
Reads text from a character-input stream, buffering characters so as to provide
for the efficient reading of characters, arrays, and lines.
Example: BufferedReader Demo
15
Solution
• One natural way is to use a StringTokenizer and a Stack. Stack is a class (de-
fined in java.util) that implements an easy-to-use last-in, first-out (LIFO) stack of
objects.
16
Example: Reverse string by word using StringTokenizer and a stack
17
Solution
• The String class has a number of methods for dealing with documents in a partic-
ular case. toUpperCase() and toLowerCase() each return a new string that is
a copy of the current string, but converted as the name implies.
• equalsIgnoreCase() tells you if all characters are the same regardless of case.
Solution:
18
1. Main difference between equals() method and == operator is that one is method
and other is operator.
Both expression gives you String object, but there is subtle difference between them.
• When you create String object using new() operator, it always create a new ob-
ject in heap memory.
• On the other hand, if you create object using String literal syntax e.g. "Java", it
may return an existing object from String pool (a cache of String object in Perm
gen space, which is now moved to heap space in recent Java release), if it’s al-
ready exists.
• Otherwise it will create a new string object and put in string pool for future re-
use.
19
Figure 3.1: Difference between String literal and String object
20
Solution: Indent Demo
2. To undent (remove space), use substring to generate a string that does not
include the leading spaces. Be careful of inputs that are shorter than the amount
you are removing!
Solution: Undent Demo
21
3.11 Entering Nonprintable Characters
Problem
You need to put nonprintable characters into strings.
Solution
Use the backslash character and one of the Java string escapes.
3.11.1 Assignment
1. WAP to put a \t in a string.
• The trim() method in java checks this Unicode value before and after the string,
if it exists then removes the spaces and returns the omitted string.
• trim() returns the omitted string with no leading and trailing spaces.
22
Example:
23