Anda di halaman 1dari 20

String Handling

• in Java
– string is a sequence of characters
• But not character arrays rather object of String.
• Fixed and immutable.
– a new String object is created for modified strings.
• StringBuffer
– For modifiable strings
• Both String & StringBuffer are final.
• Create
• Search
• Modify
• Compare 2-CSE-'C'sec sastra 2017-2018
• String creation
– String objects that are created using literal are stored in a special memory
area known as string constant pool.
– literal
• String s1 = “java”;
• String s2 = “java”;
• Only one object is created. While accessing s2, the reference s1 will be returned.
– new keyword
• String()
– String s = new String();
• String(char chars[ ])
– char chars[] = { 'a', 'b', 'c' };
– String s = new String(chars);
• String(String strObj)
– String s1 = new String(s);
• String(char chars[ ], int startIndex, int numChars)
– String s = new String (chars, 1, 2);
• String(byte asciiChars[ ])
– byte ascii[] = {65, 66, 67, 68, 69, 70 };
– String s= new String(ascii);
• String(byte asciiChars[ ], int startIndex, int numChars)
– String s1 = new String(ascii,2,5);

2-CSE-'C'sec sastra 2017-2018


• String Length
• The length of a string is the number of
characters that it contains. To obtain this
value, call the length( ) method
• int length( ) The following fragment prints "3",
since there are three characters in the string s:
• char chars[] = { 'a', 'b', 'c' };
• String s = new String(chars);
System.out.println(s.length());

2-CSE-'C'sec sastra 2017-2018


• String Concatenation
– Java converts data into its string representation during
concatenation
• valueOf() - returns a string that contains the human-readable
equivalent of the value
– toString()
» string representation for objects of classes
– static String valueOf(double num)
– static String valueOf(long num)
– static String valueOf(Object ob)
– static String valueOf(char chars[ ])
– There are several valueOf() methods for all the simple
data types.
– Example :int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
-For objects, valueOf( 2-CSE-'C'sec
) callssastra
the toString( )
2017-2018
• Character Extraction
– char charAt(int where)
– void getChars(int sourceStart, int sourceEnd, char target[ ],
int targetStart)
• extract more than one character at a time
• void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
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);
Output: demo
– char[ ] toCharArray( )
• convert all the characters in a String object into a character array
– byte[ ] getBytes( )
• stores the characters in an array of bytes
2-CSE-'C'sec sastra 2017-2018
• String Comparison
– Comparing the whole Strings
• boolean equals(Object str)
– Compares the original content for equality.
» returns true if the strings contain the same characters in the same order( considers
the case also)
• boolean equalsIgnoreCase(String str)
– Same as equals but ignores the case
• int compareTo(String str)
– compares values lexicographically and returns an integer value that describes if first
string is less than, equal to or greater than second string.
– Less than zero - The invoking string is less than str.
– Greater than zero - The invoking string is greater than str.
– Zero - The two strings are equal.
• int compareToIgnoreCase(String str)
– Same as compareTo but ignores the case
• = = operator
– compares references not values.
– Other comparison methods
• boolean startsWith(String str); Foobar".endsWith("bar")
• boolean endsWith(String str); "Foobar".startsWith("Foo") are both true
• boolean startsWith(String str, int startIndex) "Foobar".startsWith("bar", 3)
2-CSE-'C'sec sastra 2017-2018 returns true.
• boolean regionMatches(int startIndex,
String str2,
int str2StartIndex,
int numChars )
• boolean regionMatches(boolean ignoreCase,
int startIndex,
String str2,
int str2StartIndex,
int numChars )

2-CSE-'C'sec sastra 2017-2018


• Searching on Strings
– int indexOf(int ch)
• search for the first occurrence of a character
– int lastIndexOf(int ch)
• search for the last occurrence of a character
– int indexOf(int ch, int startIndex)
– int lastIndexOf(int ch, int startIndex)
• specify a starting point for the search
– int indexOf(String str)
– int lastIndexOf(String str)
• search for the first or last occurrence of a substring
– int indexOf(String str, int startIndex)
– int lastIndexOf(String str, int startIndex)
• specify a starting point for the search

2-CSE-'C'sec sastra 2017-2018


• Modifying the Strings
– String substring(int startIndex)
• returns a copy of the substring that begins at startIndex and runs to the
end of the invoking string
– String substring(int startIndex, int endIndex)
• String returned contains all the characters from the beginning index,
up to, but not including, the ending index
– String concat(String str)
• Appends the str to the invoking string
– String replace(char original, char replacement)
• replaces all occurrences of one character in the invoking string with
another character
– String trim( )
• leading and trailing whitespace has been removed
– String toLowerCase( )
– String toUpperCase( ) 2-CSE-'C'sec sastra 2017-2018
No. Method Description

1 char charAt(int index) returns char value for the particular


index

2 int length() returns string length

3 static String format(String format, Object... args) returns formatted string

4 static String format(Locale l, String format, Object... returns formatted string with given
args) locale

5 String substring(int beginIndex) returns substring for given begin


index

6 String substring(int beginIndex, int endIndex) returns substring for given begin
index and end index

7 boolean contains(CharSequence s) returns true or false after matching


the sequence of char value

8 static String join(CharSequence delimiter, returns a joined string


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? returns a joined string


extends CharSequence> elements)

10 boolean equals(Object another) checks the equality of string with


2-CSE-'C'sec sastra 2017-2018
object
11 boolean isEmpty() checks if string is empty

12 String concat(String str) concatenates specified string

13 String replace(char old, char new) replaces all occurrences of specified char value

14 String replace(CharSequence old, replaces all occurrences of specified


CharSequence new) CharSequence

15 String trim() returns trimmed string omitting leading and


trailing spaces

16 String split(String regex) returns splitted string matching regex

17 String split(String regex, int limit) returns splitted string matching regex and limit

18 String intern() returns interned string

19 int indexOf(int ch) returns specified char value index

20 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given
2-CSE-'C'sec sastra index
2017-2018
21 int indexOf(String substring) returns specified substring index

22 int indexOf(String substring, returns specified substring index


int fromIndex) starting with given index
23 String toLowerCase() returns string in lowercase.

24 String toLowerCase(Locale l) returns string in lowercase using


specified locale.
25 String toUpperCase() returns string in uppercase.

26 String toUpperCase(Locale l) returns string in uppercase using


specified locale.

2-CSE-'C'sec sastra 2017-2018


2-CSE-'C'sec sastra 2017-2018
2-CSE-'C'sec sastra 2017-2018
• JDK 8 adds a new method to String called join( )
• It is used to concatenate two or more strings, separating each string with a delimite
• static String join(CharSequence delim, CharSequence . . . strs)
• Here, delim specifies the delimiter used to separate the character sequences specified
by strs.
// Demonstrate the join() method defined by String.
class StringJoinDemo
{
public static void main(String args[]) {
String result = String.join(";", "Alpha", "Beta", "Gamma");
System.out.println(result);
result = String.join(“ ", "John", "ID#: 569", "E-mail: John@HerbSchildt.com");
System.out.println(result);
}
}
Output:
D:\java2016\program>java StringJoinDemo
Alpha;Beta;Gamma
John ID#: 569 E-mail: John@HerbSchildt.com
2-CSE-'C'sec sastra 2017-2018
• StringBuffer
– String represents fixed-length, immutable character
sequences.
– StringBuffer represents growable and writeable
character sequences
• characters and substrings inserted in the middle or
appended to the end
• will automatically grow to make room for such addition
• StringBuffer( ) // 16 characters without reallocation
• StringBuffer(int size) // explicitly sets the size
• StringBuffer(String str) // 16 more characters
– Reallocation is costly in time and also frequent reallocations can
fragment memory

2-CSE-'C'sec sastra 2017-2018


• int length( )
– Current length of the buffer can be found
• int capacity( )
– total allocated capacity can be found
• void ensureCapacity(int capacity)
– preallocate room for a certain number of characters after a StringBuffer has been constructed
• void setLength(int len)
– If you call setLength( ) with a value less than the current value returned by length( ), then the
characters stored beyond the new length will be lost
– When you increase the size of the buffer, null characters are added to the end of the existing
buffer
• void ensureCapacity(int capacity)
– Current capacity > ensured capacity
• Returns the old capacity as the capacity ensured is less than the old capacity returns the old capacity as
the capacity
– Current capacity < enusred capacity
• Twice the old capacity + 2
– Twice the old capacity+2 < ensured size
» Set the enusred size as new capacity
– Current capacity == ensured capacity
• Old capacaity will be set
– If the contents inside the buffer exceeds the capacity of the buffer because of the operations
like append, the capacity will be increased using the formula
• Twice old+2

2-CSE-'C'sec sastra 2017-2018


• char charAt(int where)
– Get the character at a specified position
• void setCharAt(int where, char ch)
– Set the char at a specified position and replaces the
old char in that place
• void getChars(int sourceStart, int sourceEnd,
char target[ ], int targetStart)
– Extract a substring and store it in a character array

2-CSE-'C'sec sastra 2017-2018


• StringBuffer append(String str)
• StringBuffer append(int num)
• StringBuffer append(Object obj)
– Appends the string, integer, Object repectively on a
invoking string object

• StringBuffer insert(int index, String str)


• StringBuffer insert(int index, char ch)
• StringBuffer insert(int index, Object obj)

• StringBuffer reverse( )
• StringBuffer delete(int startIndex, int endIndex)
– End index is not included
• StringBuffer deleteCharAt(int loc)
2-CSE-'C'sec sastra 2017-2018
• StringBuffer replace(int startIndex, int endIndex,
String str)
– Length of str > endindex – start index
• Remaining values will be appended into stringbuffer and increase
the size of the string
– Length of string < end index – start index
• The characters in the exceeding positions will be deleted.

• String substring(int startIndex)


• String substring(int startIndex, int endIndex)

2-CSE-'C'sec sastra 2017-2018

Anda mungkin juga menyukai