0% found this document useful (0 votes)
9 views6 pages

Ch-10 Strings in Java

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

Using Library Classes (Chap – 10)

Strings in Java
A string is a sequence of one or more characters enclosed in double quotes. In Java, strings
are class objects instantiated using two classes defined in java.lang:
1. String
2. StringBuffer

Using the String class


Creation (Syntax): String <stringName> = new String ( );

For e.g., String s = new String ( ); // creates an empty string


The string creation process can also be written individually as:
String s; // reference creation
s = new String ( ); // memory allocation

Initialization:
1. Using a String literal:
String s = new String (“May”);
String s = “May”;
String x = new String(s); // creates String x from String s

2. Using a Scanner / Inputstream object:


String s = br.readLine ( ); // br is a BufferedReader object
String s = sc.next ( ); // inputs a word - sc is a Scanner object
String s = sc.nextLine ( ); // inputs a text - sc is a Scanner object

3. Using a Character Array:


char chrs[ ] = { „S‟, „u‟, „n‟, „d‟, „a‟, „y‟ } ;
String s1 = new String (chrs);
String s2 = new String (chrs, 0, 3); // creates string “Sun”
String s3 = new String (chrs, 3, 3); // creates string “day”
String Accessor Methods:

Method Format Description + Example


Returns the number of characters in the string.
String a = "Work hard" ;
int length ( )
System.out.println(a.length( ));
System.out.println("Java".length( ));
Returns the character from the ith position of a string.
String a = "Application" ;
char charAt (int i)
char c = a.charAt (3);
System.out.println("Computer".charAt (4 ));
Returns the position for the first occurrence of the
int indexOf (int ch) specified character ch.
String x = "Tomorrow" ; int p = x.indexOf ('o');
returns the position for the first occurence of the
int indexOf (int ch, int i) specified character ch from the specified position.
System.out.println("success".indexOf ('s',1 ));
Returns the position for the last occurrence of the
specified character.
int lastIndexOf (int ch)
String y = "Mississippi" ;
System.out.println(y.lastIndexOf('s'));
Returns the substring that begins from the nth index.
String substring (int n) String x = "Halfyearly" ;
System.out.println(x.substring(4));
Returns the substring that begins from the nth
String substring (int n, int m) character upto (m-1)th character.
System.out.println("Hello".substring(0,4 ));
Returns true, if two string objects are exactly same,
boolean equals (String s) including their case.
System.out.println("BlueJ".equals("bluej" ));
Same as above, but differing only in their case.
boolean equalsIgnoreCase (String s) String a = "Run" ; String b = "run" ;
System.out.println(a.equalsIgnoreCase(b ));
Compares two strings of same case in dictionary
order. s1.compareTo (s2) returns
int compareTo (String obj) < 0 (s1<s2), > 0 (s1>s2), 0 (s1=s2)
System.out.println("lock".compareTo("look" )); // -12
System.out.println("loc".compareTo("lock" )); // -1
Same as above, but ignores the case of the letters.
int compareToIgnoreCase (String obj) String x = "Aptitude" ; String y = "attitude" ;
System.out.println(x.compareToIgnoreCase(y ));
Returns a new string after replacing all occurrences of
String replace(char old, char new)
the old character with the new character in a given
string.
String x = "Truck".replace('u', 'a' );
Returns a new string after replacing all occurrences of
an old substring with the new substring of the invoked
String replace (String old, String new) string.
String x = "You are good when your actions are good";
System.out.println (x.replace("good", "bad" ));
Returns a new after removing any leading or trailing
String trim ( ) spaces from the invoked string.
String s = "" Computer is Fun "".trim( );
Returns a new string after joining a given string with
String concat (String s) the specified string. String x = "Annual" ;
System.out.println(x.concat(" Exam"));
Returns a new string after converting all lower case
String toUpperCase ( ) letters of a given string to upper case.
System.out.println("Test".toUpperCase( ));
Returns a new string after converting all upper case
String toLowerCase ( ) letters of a given string to lower case.
System.out.println("coMpuTer".toLowerCase( ));
Returns a character array after transferring all
characters of a string into it.
char[ ] toCharArray ( ) String s = "Java Creator" ;
char cha[ ] = s.toCharArray( );
System.out.println(cha[0] = = s.charAt (5));
Returns a string representation of the argument which
may be of any primitive or reference data type.
int iv = 4 ; double fv = 0.5 ;
String valueOf (arg)
String x = String.valueOf (iv); // "4"
String y = String.valueOf (fv);
System.out.println(x + y ); // "40.5"

Using ‘+’ operator:


For e.g.,
int m = 5 , n = 7 ;
System.out.println(m + n + “ = m+n”) ;
System.out.println(“m + n = “ + m + n) ;
System.out.println(“m + n = “ +(m + n)) ;
System.out.println(“24” + „A‟) ; // 24A
System.out.println('A' + „1‟ + 'C') ; // 181

String x = “Con” ; String y = “cate” ;


System.out.println(x.concat(y) + “nation”) ; // "Concatenation"
String Array: A list of strings is a 1D array of strings.
Creation (Syntax): String arrayname [ ] = new String [size];
For e.g., String name [ ] = new String [3];

Initialization:
Syntax: String array-name [ ] = { “String1”, “String2”,…,”StringN” };

For e.g., String mth[ ] = { “Jan”, “Feb”, “Mar”, “Apr”, “May” } ;


String arr[ ] = { “East”, “West”, “North”, “South” } ;
System.out.println(arr.length) ; // gives number of strings
Accession:
Each individual string can be accessed as:
System.out.println(mth[1]) ; // “Feb”
System.out.println(arr[2].length( )) ; // 5

Each individual character of a string can be accessed as:


System.out.println(mth[4].charAt(0)) ; // „M‟
System.out.println(arr[0].charAt(0)) ; // „E‟

// To check for a palindrome string


import java.util.* ;
class Palin {
public static void main(String args[ ]) {
int n, i ;
String str, revstr = “”;
Scanner sc = new Scanner (System.in);
System.out.println(“String ”) ;
str = sc.next( ) ; // string input
n = str.length( ) ;
for (i = n–1 ; i >= 0 ; i– –)
revstr = revstr + str.charAt(i) ;
if (str.equals(revstr))
System.out.println(“Palindrome”) ;
else System.out.println(“Not Palindrome”) ;
}
} // end of main and class

// To print strings in increasing order of their lengths


import java.util.* ;
class Arrange {
public static void main(String args[ ]) {
int i, j, m, n ;
String sa[ ] = new String[3] ; // String array
Scanner sc = new Scanner (System.in);
System.out.println(“Enter 3 words : “) ;
for (i = 0; i < 3 ; i++)
sa[ i ] = sc.next( ) ; // input string array
// bubble sorting
for (i = 0 ; i < 2 ; i++) {
for (j = 0 ; j < 2 – i ; j++) {
m = sa[j].length ( );
n = sa[ j+1 ].length( ) ;
if (m > n) {
// swap strings
String t1 = sa[j]; String t2 = sa[ j+1] ;
sa[ j ] = t2 ;
sa[ j+1] = t1 ;
} // end of if
} // end of inner for loop
} // end of outer for loop
for(i = 0; i < 3 ; i++)
System.out.println(sa[ i ]) ;
} // end of main
} // end of class

String StringBuffer

It creates strings of fixed length. It creates strings of flexible length.

The contents of the string cannot T h e c o n te n ts o f th e s trin g c a n b e


be changed. changed in both length and contents.

Using the StringTokenizer class


The processing of text consists of parsing the text into a set of discrete parts or tokens.
A StringTokenizer breaks an input string into tokens using a delimiter pattern which by default is
a white space character (space, tab, newline etc.).
Syntax:
StringTokenizer stObj = new StringTokenizer (String str);
StringTokenizer stObj = new StringTokenizer (String str, String pattern);
Here, pattern specifies a set of one or more delimiters like comma(“ , “), semicolon(“ ; “), colon(“
: “), or a period (“.”).
The StringTokenizer class of java.util package contains the following methods:

Method Description

nextToken( ) Returns the next token as a String.


hasMoreTokens( ) Returns true, if one or more tokens remain in the string, and false if there are none.

countTokens( ) Returns the number of tokens to be parsed, using the current set of delimiters.

// Parsing an input stream text into tokens


import java.util.* ;
class ParseText {
public static void main(String args[ ]) {
Scanner sc = new Scanner (System.in) ;
StringTokenizer st ;
System.out.println(“Enter words separated by a comma and space”) ;
st = new StringTokenizer(sc . nextLine( ), “, “) ;
System.out.println(“No. of words : “ +st.countTokens( )) ;
while (st.hasMoreTokens( )) {
System.out.println(st.nextToken( )) ;
}
} // end of main
} // end of class

You might also like