Chapter 03 - Arrays & Strings Part-02 Strings

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

Object Oriented Programming

19CSE (2nd Semester)


Chapter#03: Arrays & Strings
Part-02 Strings

1
PART-02
STRINGS

2
Outline
What are Strings?
String & StringBuffer Classes
String v/s StringBuffer Classes
Different ways to create strings
Using string literals
Using new keyword
String Class methods
Example Java programs
3
What are Strings?
Java string is a sequence of characters. They are
objects of type String.
Once a String object is created it cannot be
changed. Stings are Immutable.
To get changeable strings use the class called
StringBuffer.
String is the only class where operator overloading
is supported in java. We can concat two strings
using + operator. For example "a"+"b"="ab"
String and StringBuffer classes are declared final,
so there cannot be subclasses of these classes. 4
StringBuffer Class
Implemented as a mutable sequence of
characters
Can be modified
Does not provide a set of methods for:
Comparing strings
Locating characters and substrings within a string
Created and stored in a buffer having a set
character capacity

5
String V/S StringBuffer classes
String class
Preferred class for displaying or comparing strings
that tend to remain constant
StringBuffer class
Should be used for applications that require:
Individual character additions
Modifications
Multiple text edits

6
Different Ways to Create String
1)Using string literal
 This is the most common way of creating string. In this case a
string literal is enclosed with double quotes.
String str = "abc";

public class Demo{


public static void main(String[] args)
{
String s1 = "Hello Java";
System.out.println(s1);
}
}
7
Different Ways to Create String
2) Using new Keyword
 We can create a new string object by using new operator
that allocates memory for the object.
String str = new String("abc");
char[] a = {'a', 'b', 'c'};
String str2 = new String(a);
public class Demo{
public static void main(String[] args) {
String s1 = new String("Hello Java");
System.out.println(s1);
}
}
8
String Class Methods
1) length( )
int length( )
The length() method returns the length of the
string.
Eg: System.out.println(“Hello”.length()); // prints 5
2) charAt( )
public char charAt(int index)
 Returns the character at the specified index. An index ranges from 0
to length() - 1. The first character of the sequence is at index 0, the
next at index 1, and so on, as for array indexing.
Example: char ch;
ch = “abc”.charAt(1); // ch = “b” 9
String Class Methods
3) equals( )
public boolean equals(String obj)
 The Compares the invoking string to the specified object. The
result is true if and only if the argument is not null and is a
String object that represents the same sequence of characters
as the invoking object.
 Example: boolean b=“object”.equals(“Object”)// output=?
4) equalsIgnoreCase( )
public boolean equalsIgnoreCase(String obj)
 Compares this String to another String, ignoring case
considerations. Two strings are considered equal ignoring case if
they are of the same length, and corresponding characters in
the two strings are equal ignoring case.
 Example: boolean b=“object”.equalsIgnoreCase(“Object”);
// output=?
10
String Class Methods
5) startsWith( )
public boolean startsWith(String prefix)
 This method tests if this string starts with the specified prefix.
 Examle:
“Figure”.startsWith(“Fig”); // true

public boolean startsWith(String prefix, int toffset)


 Tests if this string starts with the specified prefix beginning at a
specified index.
 prefix - the prefix and toffset - where
to begin looking in the string.
 Example: figure”.startsWith(“gure”, 2);
 // true
11
6) endsWith( )
String Class Methods
public boolean endsWith(String suffix)
 Tests if this string ends with the specified suffix.
 Example:
“Figure”.endsWith(“re”); // true
7)CompareTo( )
public int compareTo(String anotherString)
 Compares two strings lexicographically.
 The result is a negative integer if this String object lexicographically
precedes the argument string.
 The result is a positive integer if this String object lexicographically follows
the argument string.
 The result is zero if the strings are equal.
 compareTo returns 0 exactly when the equals(Object) method would return
true.
 8) compareToIgnoreCase( )
public int compareToIgnoreCase(String str) 12
String Class Methods
9) indexOf( )
Searches for the first occurrence of a character or substring.
Returns -1 if the character/substring does not occur.
public int indexOf(int ch)
 Returns the index within this string of the first occurrence of the
specified character.
public int indexOf(String str)
 Returns the index within this string of the first occurrence of the
specified substring.
public int indexOf(int ch, int fromIndex)
 Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
public int indexOf(String str, int fromIndex)
 Returns the index within this string of the first occurrence of
the specified substring, starting at the specified index. 13
String Class Methods
8) indexOf( )
 Examples1:
String str = “How was your day today?”;
str.indexof(‘t’); //output?
 Example2:
String str = “How was your day today?”;
str.indexof(“was”); //output?
 Example3:
String str = “How was your day today?”;
str.indexof(‘a’, 9);
 Example4:
String str = “How was your day today? It was good”;
str(“was”, 9);
14
String Class Methods
10) lastIndexOf( )
 Searches for the last occurrence of a character or substring.
Returns -1 if the character/substring does not occur.
 The methods are similar to indexOf().
public int lastIndexOf(int ch)
 Returns the index within this string of the last occurrence of the
specified character.
public int lastIndexOf(String str)
 Returns the index within this string of the last occurrence of the
specified substring.
public int lastIndexOf(int ch, int fromIndex)
 Returns the index within this string of the last occurrence of the
specified character, starting the search at the specified index.
public int LastIndexOf(String str, int fromIndex)
 Returns the index within this string of the last occurrence of
15
the specified substring, starting at the specified index.
String Class Methods
11) subString( )
 Returns a new string that is a substring of this string.
public String substring(int beginIndex)
 The substring begins with the character at the
specified index and extends to the end of this string.
 Example:
"unhappy".substring(2) //returns "happy"
public String substring(int beginIndex, int endIndex)
 Returns a new string that is a substring of this string
starting and ending from index.
 Example:
"smiles".substring(1, 5) returns "mile“//output=?
16
String Class Methods
12) conCat( )
 Concatenates the specified string to the end of this string.
 If the length of the argument string is 0, then this String
object is returned.
 Otherwise, a new String object is created, containing the
invoking string with the contents of the str appended to it.
public String concat(String str)
 Eg: "to".concat("get").concat("her") returns "together"
 The + operator is used to concatenate two or more strings.
Eg: String myname = “Harry”
String str = “My name is” + myname+ “.”;
• For string concatenation the Java compiler converts an operand
to a String whenever the other operand of the + is a String
object.
17
String Class Methods
13) Replace ( )
 Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
public String replace(char oldChar, char newChar)
 Example:
"mesquite in your cellar".replace('e', 'o') returns "mosquito in
your collar"
14) trim()
 Returns a copy of the string, with leading and trailing whitespace
omitted.
public String trim()
 Example:
String s = “ Hi Mom! “.trim();
//output//S = “Hi Mom!”
 Concatenates the specified string to the end of this string.
18
String Class Methods
15) toLowerCase ( )
 Converts all of the characters in a String to lower case.
public String toLowerCase()
 Example: “HELLO THERE”.toLowerCase();

16) toUpperCase( )
 Converts all of the characters in this String to upper
case.
 Example: “hello there”.toUpperCase();

19
String Class Methods
Conversion methods
 Convert strings to and from primitive numerical data
types
 General-purpose methods
 Typically invoked by preceding the method name with
the String class name and a period

21
Programs
public class countVowLetSpc
{
Java program to count
public static void main(String[] args) number of vowels, letters and
{ spaces in the string text
// Text string to be analyzed
String text = "To be or not to be, that is the question;"
+"Whether ‘tis nobler in the mind to suffer"
+" the slings and arrows of outrageous fortune,"
+" or to take arms against a sea of troubles,"
+" and by opposing end them?";
int spaces = 0, vowels=0, letters=0; // Count of spaces,vowels and letters
// Analyze all the characters in the string
int textLength = text.length(); // Get string length
for(int i = 0; i < textLength; i++)
{
char ch = Character.toLowerCase(text.charAt(i));
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') //check for vowels
vowels++;
if(Character.isLetter(ch)) //check for letters
letters++;
if(Character.isWhitespace(ch)) //check for spaces
spaces++;
}
System.out.println("The text contains:");
System.out.println("vowels:"+vowels+"\nconstants:"+(letters-vowels)+"\nandOUTPUT spaces:"+spaces);
The text contained vowels: 60
} consonants: 93
} spaces: 37
Programs
public class CountTheAnd
{
public static void main(String[] args)
{
// Text string to be analyzed
String text = "To be or not to be, that is the question;"
+ " Whether ‘tis nobler in the mind to suffer"
Java program to find number
+ " the slings and arrows of outrageous fortune," of “ands” and number of
+ " or to take arms against a sea of troubles,"
+ " and by opposing end them?";
“thes” in the string text
int andCount = 0; // Number of and’s
int theCount = 0; // Number of the’s
int index = -1; // Current index position
String andStr = "and"; // Search substring
String theStr = "the"; // Search substring
// Search forwards for “and”
index = text.indexOf(andStr); // Find first ‘and’
while(index >= 0)
{
++andCount; This program will
index += andStr.length(); // Step to position after last ‘and’
index = text.indexOf(andStr, index);
produce the following
} output:
// Search backwards for “the”
index = text.lastIndexOf(theStr); // Find last ‘the’
The text contains 2 ands
while(index >= 0) The text contains 5 thes
{
++theCount;
index -= theStr.length(); // Step to position before last ‘the’
index = text.lastIndexOf(theStr, index);
}
System.out.println("The text contains " + andCount + " ands\n" + "The text contains " + theCount + " thes");
}
}

You might also like