0
STRING AND STRING
MANIPULATION
Contents:
1.What Is String?
2.Creating and Using Strings
Declaring, Initializing, Reading a...
WHAT IS STRING?
 String is:
 A sequence of characters
 Each character is a Unicode character
 Represented by the Strin...
java.lang.String
 We use java.lang.String to work with strings in Java
 String objects contain an immutable (read-only) ...
java.lang.String
 String objects are like arrays of characters (char[])
 Have fixed length “string”.length()=6…
 Elemen...
java.lang.String
Example:
String s = "Hidaya Institute of Science & Tchnology.";
System.out.println("s= "+s);
System.out.p...
DECLARING, INITIALIZING
 Declaring
 We use Java String class for declaring string variables:
 Not initialized variables...
STRING OBJECTS ARE IMMUTABLE

String s1 = "Java"; //Statement 1
String s2 = s1; //Statement 2
s2 = s1.concat("Is"); //Sta...
STRING OBJECTS ARE IMMUTABLE

Java
s1
s2
Statement 3:Statement 3: s2=s1.concat(“Is”);s2=s1.concat(“Is”);
StringString
ref...
STRING OBJECTS ARE IMMUTABLE

Java
s1
s2
Statement 3:Statement 3: s2=s2+”Fun”;s2=s2+”Fun”;
StringString
referencereferenc...
READING AND PRINTING STRINGS
 Reading strings from the console
 java.util.Scanner input=new java.util.Scanner(System.in)...
MANIPULATING STRINGS
 Comparing Strings:
 There are a number of ways to compare two strings:
 Dictionary-based string c...
COMPARING STRINGS (2)
 Equality checking by equalsIgnoreCase()
 Performs case-insensitive compare
 Returns boolean valu...
COMPARING STRINGS – EXAMPLE
 Finding the first in a lexicographical order string from a given list
of strings
String[] to...
java.lang.STRING
 Operators == and != does not check for equality!
 These operators returns boolean value, but check if ...
CONCATENATING STRINGS
 There are two ways to combine strings:
 Using the concat() method
 Using the + or the += operato...
CONCATENATING STRINGS –
EXAMPLE
String firstName = “Asad";
String lastName = “Khan";
String fullName = firstName + " " + l...
SEARCHING STRINGS
 Finding a character or substring within given string
 First occurrence
 First occurrence starting at...
SEARCHING STRINGS – EXAMPLE
String str = "Java Programming Course";
int index = str.indexOf("Java"); // index = 0
index = ...
EXTRACTING SUBSTRINGS
 Extracting substrings
 str.substring(int beginIndex, int endIndex)
 lastIndex is not included
 ...
SPLITTING STRINGS
 To split a string by given separator(s) use the following
method:
 String regex – String with special...
SPLITTING STRINGS - EXAMPLE
String ListOfCourses = "Java, ASP, PHP, Linux.";
String[] Courses = ListOfCourses.split("[ ,.]...
OTHER STRING OPERATIONS
Replacing Substrings, Changing Character Casing, Trimming
REPLACING SUBSTRINGS replace(String, String) – replaces all occurrences of
given string with another
 The result is new ...
TRIMMING WHITE SPACE
 Using method trim()
String s = " example of white space ";
String clean = s.trim();
System.out.prin...
BUILDING AND MODIFYING
STRINGS
Using StringBuilder Class
CONSTRUCTING STRINGS
 Strings are immutable
 concat(), replace(), trim(), ... return new string, do not modify
the old o...
CHANGING THE CONTENTS OF A
STRING – STRINGBUILDER
 Use the java.lang.StringBuilder class for modifiable strings of
charac...
THE STRINGBUILDER CLASS
 StringBuilder keeps a buffer memory, allocated in advance
 Most operations use the buffer memor...
THE STRINGBUILDER CLASS (2)
 StringBuilder(int capacity) constructor allocates in advance
buffer memory of a given size
...
THE STRINGBUILDER CLASS (3)
 append(…) appends string or other object after the last character
in the buffer
 delete(int...
STRINGBUILDER – EXAMPLE
 Extracting all capital letters from a string
public static String extractCapitals(String s) {
St...
HOW THE + OPERATOR DOES STRING
CONCATENATIONS?
 Consider following string concatenation:
 It is equivalent to this code:...
METHOD toString()
 All classes have this public virtual method derived from
Object class
 Returns a human-readable, cult...
Upcoming SlideShare
Loading in...5
×

11- String and string builder JAVA

181

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
181
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
28
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "11- String and string builder JAVA"

  1. 1. STRING AND STRING MANIPULATION Contents: 1.What Is String? 2.Creating and Using Strings Declaring, Initializing, Reading and Printing 1.Manipulating Strings Comparing, Concatenating, Searching, Extracting Substrings, Splitting 1.Other String Operations Replacing Substrings, Deleting Substrings, Changing Character Casing, Trimming 5.Building and Modifying Strings Using StringBuilder Class 5.Formatting Strings
  2. 2. WHAT IS STRING?  String is:  A sequence of characters  Each character is a Unicode character  Represented by the String (java.lang.String) data type in Java  Example: String s = "Hello, Java"; H e l l o , J a v as
  3. 3. java.lang.String  We use java.lang.String to work with strings in Java  String objects contain an immutable (read-only) sequence of characters  Use Unicode in order to support multiple languages and alphabets  Stores strings in the dynamic memory (managed heap)  java.lang.String is class  It is reference type
  4. 4. java.lang.String  String objects are like arrays of characters (char[])  Have fixed length “string”.length()=6…  Elements can be accessed by index  Using charAt() method  The index is in the range 0...length()-1 String s = "Hello!"; int len = s.length(); // len = 6 char ch = s.charAt(1); // ch = 'e‘` 0 1 2 3 4 5 H e l l o ! index =index = s.charAt(index) =s.charAt(index) =
  5. 5. java.lang.String Example: String s = "Hidaya Institute of Science & Tchnology."; System.out.println("s= "+s); System.out.println("Length= "+s.length()); for (int i = 0; i < s.length(); i++) { System.out.println("s["+i+"] = "+ s.charAt(i)); }
  6. 6. DECLARING, INITIALIZING  Declaring  We use Java String class for declaring string variables:  Not initialized variables has value of nullnull  Initializing  Assigning a string literal  Assigning another string variable  Assigning the result of string operation String str; String s = "I am string literal!"; String s2 = s; String s = "I'm " + 42 + " years old.";
  7. 7. STRING OBJECTS ARE IMMUTABLE  String s1 = "Java"; //Statement 1 String s2 = s1; //Statement 2 s2 = s1.concat("Is"); //Statement 3 s2 = s2 + "Fun"; //Statement 4 System.out.println("s1 = " + s1); System.out.println("s2 = " + s2); How many String objects and reference variables are created? Two Reference Variables  s1  s2 Five String Objects/literals  “Java”  “Is”  “JavaIs”  “Fun”  “JavaIsFun” String Object Java s1 s2 String s1=“Java”;String s1=“Java”; StringString referencereference variable s1variable s1 StringString referencereference variable s2variable s2 Statement 1 creates one reference variable s1, one string object “Java” Statement 2 creates one reference variable s2 String s2=s1;String s2=s1;
  8. 8. STRING OBJECTS ARE IMMUTABLE  Java s1 s2 Statement 3:Statement 3: s2=s1.concat(“Is”);s2=s1.concat(“Is”); StringString referencereference variable s1variable s1 StringString referencereference variable s2variable s2 String ObjectString Object JavaIs String ObjectString Object Is String ObjectString Object Statement 3 creates, Two String Objects, “Java” and “JavaIs” and makes s2 refer to newly created object “JavaIs”
  9. 9. STRING OBJECTS ARE IMMUTABLE  Java s1 s2 Statement 3:Statement 3: s2=s2+”Fun”;s2=s2+”Fun”; StringString referencereference variable s1variable s1 StringString referencereference variable s2variable s2 String ObjectString Object JavaIsFun String ObjectString Object Is String ObjectString Object Statement 4 creates, Two String Objects, “Fun” and “JavaIsFun” and makes s2 refer to newly created object “JavaIsFun” JavaIs String ObjectString Object Fun String ObjectString Object
  10. 10. READING AND PRINTING STRINGS  Reading strings from the console  java.util.Scanner input=new java.util.Scanner(System.in);  Use the method input.nextLine()  Printng Strings to the console  Use methods print() and println() String s = input.nextLine(); System.out.print("Please enter your name: "); String name = input.nextLine(); System.out.println(name);
  11. 11. MANIPULATING STRINGS  Comparing Strings:  There are a number of ways to compare two strings:  Dictionary-based string comparison  Case-insensitive  Case-sensitive Comparing, Concatenating, Searching, Extracting Substrings, Splitting int result = str1.compareToIgnoreCase(str2); // result == 0 if str1 equals str2 // result < 0 if str1 if before str2 // result > 0 if str1 if after str2 str1.compareTo(str2);
  12. 12. COMPARING STRINGS (2)  Equality checking by equalsIgnoreCase()  Performs case-insensitive compare  Returns boolean value  The case-sensitive equals() method if (str1.equalsIgnoreCase(str2)){ … } if (str1.equals(str2)){ … }
  13. 13. COMPARING STRINGS – EXAMPLE  Finding the first in a lexicographical order string from a given list of strings String[] towns = {"Jamshoro", “Hyderabad", "Qasimabad","Latifabad", "Kotri", "Heerabad"}; String firstTown = towns[0]; for (int i=1; i<towns.length; i++) { String currentTown = towns[i]; if (currentTown.compareTo(firstTown) < 0) { firstTown = currentTown; } } System.out.println("First town: " + firstTown);
  14. 14. java.lang.STRING  Operators == and != does not check for equality!  These operators returns boolean value, but check if the addresses of the object are equal  Use equals() and equalsIgnoreCase() instead String str1 = new String("Hello"); String str2 = str1; System.out.println((str1==str2)); // true String str1 = "Hello"; String str2 = "Hello"; System.out.println((str1==str2)); // true!!! String str1 = new String("Hello"); String str2 = new String("Hello"); System.out.println((str1==str2)); // This is false!
  15. 15. CONCATENATING STRINGS  There are two ways to combine strings:  Using the concat() method  Using the + or the += operator  Any object can be appended to string String str = str1.concat(str2); String str = str1 + str2 + str3; String str += str1; String name = “Asad"; int age = 23; String s = name +" "+ age;// “Asad 23"
  16. 16. CONCATENATING STRINGS – EXAMPLE String firstName = “Asad"; String lastName = “Khan"; String fullName = firstName + " " + lastName; int age = 23; String nameAndAge = "Name: " + fullName + "nAge: " + age; System.out.println(nameAndAge); // Name: Asad Khan // Age: 23
  17. 17. SEARCHING STRINGS  Finding a character or substring within given string  First occurrence  First occurrence starting at given position  Last occurrence  Last occurrence before given position indexOf(String str) indexOf(String str, int fromIndex) lastIndexOf(String) lastIndexOf(String, int fromIndex)
  18. 18. SEARCHING STRINGS – EXAMPLE String str = "Java Programming Course"; int index = str.indexOf("Java"); // index = 0 index = str.indexOf("Course"); // index = 17 index = str.indexOf("COURSE"); // index = -1 // indexOf is case sensetive. -1 means not found index = str.indexOf("ram"); // index = 9 index = str.indexOf("r"); // index = 6 index = str.indexOf("r", 7); // index = 9 index = str.indexOf("r", 10); // index = 20 00 11 22 33 44 55 66 77 88 99 1010 1111 1212 …… JJ aa vv aa PP rr oo gg rr aa mm mm …… i = s.charAt(i) =) =
  19. 19. EXTRACTING SUBSTRINGS  Extracting substrings  str.substring(int beginIndex, int endIndex)  lastIndex is not included  str.substring(int beginIndex) String filename = "C:PicsRila2005.jpg"; String name = filename.substring(8, 16); // name is Rila2005 String filename = "C:PicsRaila2005.jpg"; String nameAndExtension = filename.substring(8); // nameAndExtension is Rila2005.jpg 00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717 1818 1919 CC :: PP ii cc ss RR ii ll aa 22 00 00 55 .. jj pp gg
  20. 20. SPLITTING STRINGS  To split a string by given separator(s) use the following method:  String regex – String with special format  We can list the character which we want to use for separator in square brackets […] String[] split(String regex) String[] parts = "Ivan; Petar,Gosho".split("[;,]"); // this wil separate the stirng into three parts // "Ivan", " Petar" and "Gosho"
  21. 21. SPLITTING STRINGS - EXAMPLE String ListOfCourses = "Java, ASP, PHP, Linux."; String[] Courses = ListOfCourses.split("[ ,.]"); System.out.println("Available Courses are:"); for (String Course : Courses) System.out.println(Course);
  22. 22. OTHER STRING OPERATIONS Replacing Substrings, Changing Character Casing, Trimming
  23. 23. REPLACING SUBSTRINGS replace(String, String) – replaces all occurrences of given string with another  The result is new string (strings are immutable) String cocktail = "Vodka + Martini + Cherry"; String replaced = cocktail.replace("+", "and"); // Vodka and Martini and Cherry CHANGING CHARACTER CASING  Using method toLowerCase() String alpha = "aBcDeFg"; String lowerAlpha = alpha.toLowerCase(); // abcdefg System.out.println(lowerAlpha);
  24. 24. TRIMMING WHITE SPACE  Using method trim() String s = " example of white space "; String clean = s.trim(); System.out.println(clean); String alpha = "aBcDeFg"; String upperAlpha = alpha.toUpperCase(); // ABCDEFG System.out.println(upperAlpha);  Using method toUpperCase()
  25. 25. BUILDING AND MODIFYING STRINGS Using StringBuilder Class
  26. 26. CONSTRUCTING STRINGS  Strings are immutable  concat(), replace(), trim(), ... return new string, do not modify the old one  Do not use "+" for strings in a loop!  It runs very inefficiently! public static string dupChar(char ch, int count){ String result = ""; for (int i=0; i<count; i++) result += ch; return result; } Bad practice. Avoid this!
  27. 27. CHANGING THE CONTENTS OF A STRING – STRINGBUILDER  Use the java.lang.StringBuilder class for modifiable strings of characters:  Use StringBuilder if you need to keep adding characters to a string public static String reverseIt(String s) { StringBuilder sb = new StringBuilder(); for (int i = s.length()-1; i >= 0; i--) sb.append(s.charAt(i)); return sb.toString(); }
  28. 28. THE STRINGBUILDER CLASS  StringBuilder keeps a buffer memory, allocated in advance  Most operations use the buffer memory and do not allocate new objects H e l l o , J a v a !StringBuilder: length() = 11 capacity() = 15 used buffer (length()) unused buffer Capacity
  29. 29. THE STRINGBUILDER CLASS (2)  StringBuilder(int capacity) constructor allocates in advance buffer memory of a given size  By default 16 characters are allocated  capacity() holds the currently allocated space (in characters)  charAt(int index) gives access to the char value at given position  length() hold the length of the string in the buffer
  30. 30. THE STRINGBUILDER CLASS (3)  append(…) appends string or other object after the last character in the buffer  delete(int start, int end) removes the characters in given range  insert(int offset, String str) inserts given string (or object) at given position  replace(int start, int end, String str) replaces all occurrences of a substring with given string  toString() converts the StringBuilder to String object
  31. 31. STRINGBUILDER – EXAMPLE  Extracting all capital letters from a string public static String extractCapitals(String s) { StringBuilder result = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char ch = s.charAt(i); if (Character.isUpperCase(ch)) { result.append(ch); } } return result.toString(); }
  32. 32. HOW THE + OPERATOR DOES STRING CONCATENATIONS?  Consider following string concatenation:  It is equivalent to this code:  Actually several new objects are created and leaved to the garbage collector  What happens when using + in a loop? String result = str1 + str2; StringBuffer sb = new StringBuffer(); sb.append(str1); sb.append(str2); String result = sb.toString();
  33. 33. METHOD toString()  All classes have this public virtual method derived from Object class  Returns a human-readable, culture-sensitive string representing the object  Most Java Platform types have own implementation of toString() FORMATTING STRINGS  Using toString()
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×