Presentation is loading. Please wait.

Presentation is loading. Please wait.

String and String Buffers

Similar presentations


Presentation on theme: "String and String Buffers"— Presentation transcript:

1 String and String Buffers

2 Java implements strings as objects of type String.
String object has been created, you cannot change the characters that comprise that string (immutable) immutable strings can be implemented more efficiently than changeable ones java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created. The String, StringBuffer, and StringBuilder classes are defined in java.lang All are declared final, which means that none of these classes may be subclassed

3 String pgm class MakeString { public static void main(String args[]) { char c[] = {'J', 'a', 'v', 'a'}; String s1 = new String(c); String s2 = new String(s1); System.out.println(s1); System.out.println(s2); }

4 Byte to String // Construct string from subset of char array. class SubStringCons { public static void main(String args[]) { byte ascii[] = {65, 66, 67, 68, 69, 70 }; } String s1 = new String(ascii); System.out.println(s1); String s2 = new String(ascii, 2, 3); // Adding new String content System.out.println(s2); This program generates the following output: ABCDEF CDE

5 String Length int length( ) s.length() Special String Operations
String Literals char chars[] = { 'a', 'b', 'c' }; String s1 = new String(chars); String s2 = "abc"; System.out.println(s1); System.out.println(s2); String Concatenation String s = "He is " + age + " years old."; Str.concat(str);

6 Box(double w, double h, double d) { width = w; height = h; depth = d;
String Conversion and toString( ) Every class implements toString( ) because it is defined by Object String toString( ) Box(double w, double h, double d) { width = w; height = h; depth = d; } public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + ".";

7 class Box { } double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; public String toString() { return "Dimensions are " + width + " by " + depth + " by " + height + "."; class toStringDemo { public static void main(String args[]) { Box b = new Box(10, 12, 14); String s = "Box b: " + b; // concatenate Box object System.out.println(b); // convert Box to string System.out.println(s); The output of this program is shown here: Dimensions are 10.0 by 14.0 by 12.0 Box b: Dimensions are 10.0 by 14.0 by 12.0

8 You can construct a String from a StringBuffer by using the constructor shown here:
String(StringBuffer strBufObj) charAt( ) To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method char charAt(int where) char ch; ch = "abc".charAt(1); assigns the value “b” to ch. getChars( ) If you need to extract more than one character at a time, you can use the getChars( ) method getChars( ) If you need to extract more than one character at a time, you can use the getChars( ) method void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart) String s = "This is a demo of the getChars method."; s.getChars(start, end, buf, 0);

9 getBytes( ) There is an alternative to getChars( ) that stores the characters in an array of bytes byte[ ] getBytes( ) toCharArray( ) If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). char[ ] toCharArray( )

10 String Comparison equals( ) and equalsIgnoreCase( ) boolean equals(Object str) boolean equalsIgnoreCase(String str) String s1 = "Hello"; String s4 = "HELLO"; s1.equals(s4); equalsIgnoreCase  s1.equalsIgnoreCase(s4);

11 regionMatches( ) The regionMatches( ) method compares a specific region inside a string with another specific region in another string boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars) boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex,

12 s1.equals(s2) (s1 == s2) startsWith( ) and endsWith( )
boolean startsWith(String str) boolean endsWith(String str) "Foobar".endsWith("bar") "Foobar".startsWith("Foo") equals( ) Versu s1.equals(s2) (s1 == s2) It is important to understand that the equals( ) method and the == operator perform two different operations. As just explained, the equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

13 • lastIndexOf( ) Searching StringsoreCase(String str) indexOf( )
compareTo( ) Often, it is not enough to simply know whether two strings are identical int compareTo(String str) int compareToIgn Searching StringsoreCase(String str) indexOf( ) Searches for the first occurrence of a character or substring. • lastIndexOf( ) Searches for the last occurrence of a character or substring. Value Meaning 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.

14 int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex) int indexOf(String str, int startIndex) int lastIndexOf(String str, int startIndex) s.indexOf('t') s.indexOf("the") s.indexOf('t', 10)

15 String substring(int startIndex)
Modifying a String Because String objects are immutable, whenever you want to modify a String, you must either copy it into a StringBuffer or StringBuilder, or use one of the following String methods substring( ) String substring(int startIndex) String substring(int startIndex, int endIndex) org.substring(10, 20); concat( ) String concat(String str) String s1 = "one"; String s2 = s1.concat("two");

16 replace( ) String replace(char original, char replacement) String s = "Hello".replace('l', 'w'); String replace(CharSequence original, CharSequence replacement) trim( ) String trim( ) String s = " Hello World ".trim();

17 Data Conversion Using valueOf( )
The valueOf( ) method converts data from its internal format into a human-readable form. 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( ) s.toUpperCase() s.toLowerCase()

18 StringBuffer Constructors StringBuffer( ) StringBuffer(int size)
StringBuffer(String str) StringBuffer(CharSequence chars) length( ) and capacity( ) The current length of a StringBuffer can be found via the length( ) method, while the total allocated capacity can be found through the capacity( ) method int length( ) int capacity( )

19 ensureCapacity( ) void ensureCapacity(int capacity) setLength( ) To set the length of the buffer within a StringBuffer object, use setLength( ). void setLength(int len)

20 charAt( ) and setCharAt( )
The value of a single character can be obtained from a StringBuffer via the charAt( ) char charAt(int where) void setCharAt(int where, char ch) append() StringBuffer append(String str) StringBuffer append(int num) StringBuffer append(Object obj)

21 insert( ) StringBuffer insert(int index, String str) StringBuffer insert(int index, char ch) StringBuffer insert(int index, Object obj) reverse( ) StringBuffer reverse( ) delete( ) and deleteCharAt( ) StringBuffer delete(int startIndex, int endIndex) StringBuffer deleteCharAt(int loc)

22 replace( ) StringBuffer replace(int startIndex, int endIndex, String str) StringBuilder J2SE 5 adds a new string class to Java’s already powerful string handling capabilities. This new class is called StringBuilder. It is identical to StringBuffer except for one important difference: it is not synchronized, which means that it is not thread-safe. The advantage of StringBuilder is faster performance. However, in cases in which you are using multithreading, you must use StringBuffer rather than StringBuilder.


Download ppt "String and String Buffers"

Similar presentations


Ads by Google