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

Module 3

theory

Uploaded by

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

Module 3

theory

Uploaded by

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

String Handling

• Java implements strings as objects of type String.


• String Constructors
– To create an empty String, you call the default
constructor.
– For example, String s = new String();
– will create an instance of String with no characters in
it.
• String(char chars[ ])
– char chars[] = { 'a', 'b', 'c' };
– String s = new String(chars);
• String(char chars[ ], int startIndex, int numChars)
– char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
– String s = new String(chars, 2, 3);
• String(String strObj)

• String(byte asciiChars[ ])
• String(byte asciiChars[ ], int startIndex, int numChars)
• String(StringBuffer strBufObj)
String Length
int length( )
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length());
Special String Operations
• String Literals
char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal
System.out.println("abc".length());
• String Concatenation
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s);

int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);

String s = "four: " + 2 + 2;


System.out.println(s);
Character Extraction

• char charAt(int where)


char ch;
ch = "abc".charAt(1);
• void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
class getCharsDemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}
Character Extraction

• getBytes( )
• toCharArray( )
– char[ ] toCharArray( )
String Comparison
• boolean equals(Object str)
• boolean equalsIgnoreCase(String str)
String Comparison
• boolean regionMatches(int startIndex, String str2,
int str2StartIndex, int numChars)
• boolean regionMatches(boolean ignoreCase,
int startIndex, String str2, int str2StartIndex,
int numChars)
• boolean startsWith(String str)
• boolean endsWith(String str)
"Football".endsWith("ball")
and
"Football".startsWith("Foot")
are both true.
String Comparison
• boolean startsWith(String str, int startIndex)
– "Football".startsWith("ball", 4)
• equals( ) Versus ==
String Comparison
• int compareTo(String str)
// A bubble sort for Strings.
class SortString
{
static String arr[] = {"Now", "is", "the", "time", "for", "all",
"good", "men“, "to", "come", "to", "the", "aid", "of",
"their", "country"
};
public static void main(String args[])
{
for(int j = 0; j < arr.length; j++)
{
for(int i = j + 1; i < arr.length; i++)
{
if(arr[i].compareTo(arr[j]) < 0)
{
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
Searching Strings
• indexOf( ) Searches for the first occurrence of
a character or substring.
• lastIndexOf( ) Searches for the last occurrence
of a character or substring.
• int indexOf(int ch)
• int lastIndexOf(int ch)
Searching Strings
• To search for the first or last occurrence of a
substring, use
– int indexOf(String str)
– int lastIndexOf(String str)
– Here, str specifies the substring.
• You can specify a starting point for the search
using these forms:
• int indexOf(int ch, int startIndex)
• int lastIndexOf(int ch, int startIndex)
• int indexOf(String str, int startIndex)
• int lastIndexOf(String str, int startIndex)
Searching Strings
Modifying a String

• substring( )
– String substring(int startIndex)
– String substring(int startIndex, int endIndex)
Modifying a String
• concat( )
– String concat(String str)
– String s1 = "one";
– String s2 = s1.concat("two");
• replace( )
– String replace(char original, char replacement)
– String s = "Hello".replace('l', 'w');
• trim( )
– String trim( )
– String s = " Hello World ".trim();
– This puts the string “Hello World” into s.
Data Conversion Using valueOf( )
• static String valueOf(double num)
• static String valueOf(long num)
• static String valueOf(Object ob)
• static String valueOf(char chars[ ])
Changing the Case of Characters Within a
String
• String toLowerCase( )
• String toUpperCase( )
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[])
{
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
StringBuffer
• StringBuffer represents growable and writeable
character sequences.
• StringBuffer may have characters and substrings
inserted in the middle or appended to the end.
• StringBuffer( )  16 chars
• StringBuffer(int size)
• StringBuffer(String str)
• StringBuffer(CharSequence chars)
StringBuffer: length( ) and capacity( )
• int length( )
• int capacity( )
// StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
• ensureCapacity( ): to set the size of the buffer.
– void ensureCapacity(int capacity)
• setLength( ):set the length of the buffer within
a StringBuffer object.
– void setLength(int len)
• charAt( ) and setCharAt( ):
– char charAt(int where)
– void setCharAt(int where, char ch)
• getChars( )
– void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart)
append( )

• StringBuffer append(String str)


• StringBuffer append(int num)
• StringBuffer append(Object obj)

// Demonstrate append().
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
insert( )

• The insert( ) method inserts one string into


another
• StringBuffer insert(int index, String str)
• StringBuffer insert(int index, char ch)
• StringBuffer insert(int index, Object obj)
// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
reverse( )
• StringBuffer reverse( )

// Using reverse() to reverse a StringBuffer.


class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
delete( ) and deleteCharAt( )
• StringBuffer delete(int startIndex, int endIndex)
• StringBuffer deleteCharAt(int loc)
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
replace( )
• StringBuffer replace(int startIndex, int endIndex,
String str)

// Demonstrate replace()
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}

You might also like