Uploaded on

Strings and String manipulation in Java

Strings and String manipulation in Java

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,518
On Slideshare
0
From Embeds
0
Number of Embeds
1

Actions

Shares
Downloads
188
Comments
0
Likes
1

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ## Introducing the StringBuffer Class StringBuffer represents strings that can be modified and extended at run time. The following example creates three new String objects, and copies all the characters each time a new String is created: String quote = "Fasten your seatbelts, "; quote = quote + "it’s going to be a bumpy night."; It is more efficient to preallocate the amount of space required using the StringBuffer constructor, and its append() method as follows: StringBuffer quote = new StringBuffer(60); // alloc 60 chars quote.append("Fasten your seatbelts, "); quote.append(" it’s going to be a bumpy night. "); StringBuffer also provides a number of overloaded insert() methods for inserting various types of data at a particular location in the string buffer. Instructor Note The example in the slide uses StringBuffer to reverse the characters in a string. A StringBuffer object is created, with the same length as the string. The loop traverses the String parameter in reverse order and appends each of its characters to the StringBuffer object by using append() . The StringBuffer therefore holds a reverse copy of the String parameter. At the end of the method, a new String object is created from the StringBuffer object, and this String is returned from the method .
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 12/04/10 07/16/96 (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##

Transcript

  • 1. Strings and Strings Manipulation
  • 2. Contents
    • What Is String?
    • Creating and Using Strings
      • Declaring, Creating, Reading and Printing
    • Manipulating Strings
      • Comparing, Concatenating, Searching, Extracting Substrings, Splitting
    • Other String Operations
      • Replacing Substrings, Deleting Substrings, Changing Character Casing, Trimming
  • 3. Contents (2)
    • Building and Modifying Strings
      • Using StringBuilder Class
    • Formatting Strings
  • 4. What Is String?
  • 5. 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"; s H e l l o , J a v a
  • 6. 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
  • 7. java.lang.String (2)
    • String objects are like arrays of characters ( char[] )
      • Have fixed length ( String.length() )
      • Elements can be accessed by index
        • Using charAt() method
        • The index is in the range 0...length()-1
    String s = "Hello!"; int len = s. l ength () ; // len = 6 char ch = s .charAt(1) ; // ch = 'e' index = s.charAt(index) = 0 1 2 3 4 5 H e l l o !
  • 8. Strings – First Example String s = &quot;Stand up, stand up, Balkan superman.&quot;; System.out.printf(&quot;s = &quot;%s&quot;%n&quot;, s); System.out.printf(&quot;s. l ength () = %d%n&quot;, s.length()); for (int i = 0; i < s.length(); i++) { System.out.printf(&quot;s[%d] = %c%n&quot;, i, s.charAt(i)); }
  • 9. Strings – First Example Live Demo
  • 10. Declaring, Creating, Reading and Printing Creating and Using Strings
  • 11. Declaring Strings
    • We use Java String class for declaring string variables:
    String str;
  • 12. Creating Strings
    • Befor e initiali zing a strin g v a riable i s equa l t o nu l l
    • Strings can be initialized by:
      • Assigning a stri n g literal to the string variable
      • Assigning the value of another string variable
      • Assigning the result of operation of type string
  • 13. Creating Strings (2)
    • Not initialized variables has value of null
    • Assigning a stri n g literal
    • Assigning another string variable
    • Assigning the result of string operation
    S tring s; // s is equal to null St ring s = &quot;I am string literal!&quot;; S tring s 2 = s; String s = &quot;I'm &quot; + 42 + &quot; years old.&quot;;
  • 14. Reading And Printing Strings
    • Reading strings from the console
      • Use the method input.nextLine()
    String s = input.nextLine();
    • Printing strings to the console
      • Use the methods print() , println() and printf()
    System.out.print(&quot;Please enter your name: &quot;); String name = input.nextLine(); System.out.printf(&quot;Hello, %s!%n&quot;, name);
  • 15. Live Demo Reading and Printing Strings
  • 16. Manipulating Strings Comparing, Concatenating, Searching, Extracting Substrings, Splitting
  • 17. Comparing Strings
    • There are a number of ways to compa re two strings:
      • D ictionary-based string comparison
        • C ase-insensitive
        • Case-sensitive
    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);
  • 18. Comparing Strings (2)
    • Equality checking by equalsIgnoreCase ()
      • Performs c ase- in sensitive compare
      • Returns boolean value
    • T he case-sensitive equals () method
    if (str1.equalsIgnoreCase(str2)){ … } if (str1.equals(str2)){ … }
  • 19. Comparing Strings (3)
    • 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(&quot;Hello&quot;); String str2 = str1; System.out.println((str1==str2)); // true String str1 = &quot;Hello&quot;; String str2 = &quot;Hello&quot;; System.out.println((str1==str2)); // true !!! String str1 = new String(&quot;Hello&quot;); String str2 = new String(&quot;Hello&quot;); System.out.println((str1==str2)); // This is false !
  • 20. Comparing Strings – Example
    • Finding the first in a lexicographical order string from a given list of strings
    String[] towns = {&quot;Sofia&quot;, &quot;Varna&quot;, &quot;Plovdiv&quot;, &quot;Pleven&quot;, &quot;Bourgas&quot;, &quot;Rousse&quot;, &quot;Yambol&quot;}; String firstTown = towns[0]; for (int i=1; i<towns. l ength; i++) { String currentTown = towns[i]; if (currentTown.compareTo(firstTown) < 0) { firstTown = currentTown; } } System.out.println(&quot;First town: &quot; + firstTown);
  • 21. Comparing Strings Live Demo
  • 22. Concatenating Strings
    • There are two ways to combine strings :
      • U sing the c onc at() method
      • Using the + or the += operator
    • Any object can be appended to string
    S tring str = str1. c oncat(str2); String str = str1 + str2 + str3; String str += str1; S tring n ame = &quot; Peter &quot;; int age = 22 ; S tring s = name + &quot; &quot; + age ; //  &quot;Peter 22&quot;
  • 23. Concatenating Strings – Example String firstName = &quot;Svetlin&quot;; String lastName = &quot;Nakov&quot;; String fullName = firstName + &quot; &quot; + lastName; System.out.println(fullName); int age = 2 6 ; String nameAndAge = &quot;Name: &quot; + fullName + &quot;nAge: &quot; + age; System.out.println(nameAndAge); // Name: Svetlin Nakov // Age: 2 6
  • 24. Concatenating Strings Live Demo
  • 25. Searching Strings
    • F ind ing a character or substring within given string
      • F irst occurrence
      • F irst occurrence starting at given position
      • Last occurrence
      • Last occurrence before given position
    i ndexOf( S tring str) i ndexOf( S tring str, int from Index) l astIndexOf( S tring) lastIndexOf(String, int fromIndex)
  • 26. Searching Strings – Example String str = &quot;Java Programming Course&quot;; int index = str.indexOf(&quot;Java&quot;); // index = 0 index = str.indexOf(&quot;Course&quot;); // index = 17 index = str.indexOf(&quot;COURSE&quot;); // index = -1 // indexOf is case sensetive. -1 means not found index = str.indexOf(&quot;ram&quot;); // index = 9 index = str.indexOf(&quot;r&quot;); // index = 6 index = str.indexOf(&quot;r&quot;, 7); // index = 9 index = str.indexOf(&quot;r&quot;, 10); // index = 20 i = s.charAt(i) = 0 1 2 3 4 5 6 7 8 9 10 11 12 … J a v a P r o g r a m m …
  • 27. Searching Strings Live Demo
  • 28. Extracting Substrings
    • Extracting substrings
      • str.substring(int beginIndex, int endIndex)
        • lastIndex is not included
      • str.substring(int beginIndex)
    S tring filename = &quot;C: Pics Rila2005.jpg&quot;; S tring name = filename. s ub s tring(8, 16 ); // name is Rila2005 S tring filename = &quot;C: Pics Summer2005.jpg&quot;; S tring nameAndExtension = filename. s ub s tring(8); // nameAndExtension is Rila2005 .jpg 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 C : P i c s R i l a 2 0 0 5 . j p g
  • 29. Extracting Substrings Live Demo
  • 30. 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 = &quot;Ivan; Petar,Gosho&quot;.split(&quot;[;,]&quot;); // this wil separate the stirng into three parts // &quot;Ivan&quot;, &quot; Petar&quot; and &quot;Gosho&quot;
  • 31. Splitting Strings - Example String listOfBeers = &quot;Amstel, Zagorka, Tuborg, Becks.&quot;; String[] beers = listOfBeers.split(&quot;[ ,.]&quot;); System.out.println(&quot;Available beers are:&quot;); for (String beer : beers) { if (!&quot;&quot;.equalsIgnoreCase(beer)) { System.out.println(beer); } }
  • 32. Splitting Strings Live Demo
  • 33. Other String Operations Replacing Substrings, Changing Character Casing, Trimming
  • 34. Replacing Substrings
    • r eplace( S tring, S tring) – replaces all occurrences of given string with another
      • The result is new string (strings are immutable)
    String cocktail = &quot;Vodka + Martini + Cherry&quot;; String replaced = cocktail.replace(&quot;+&quot;, &quot;and&quot;); // Vodka and Martini and Cherry
  • 35. Changing Character Casing
    • Using method toLowerCase()
    • Using method toUpperCase()
    S tring alpha = &quot;aBcDeFg&quot;; S tring lowerAlpha = alpha. t oLower Case (); // abcdefg System.out.println(lowerAlpha); S tring alpha = &quot;aBcDeFg&quot;; S tring upper A lpha = alpha. t oUpper Case (); // ABCDEFG System.out.println(upperAlpha);
  • 36. Trimming White Space
    • Using method trim()
    String s = &quot; example of white space &quot;; String clean = s.trim(); System.out.println(clean);
  • 37. Other String Operations Live Demo
  • 38. Building and Modifying Strings Using StringBuilder C lass
  • 39. Constructing Strings
    • Strings are immutable
      • c oncat() , r eplace() , t rim() , ... return new string, do not modify the old one
    • Do not use &quot; + &quot; for strings in a loop!
      • It runs very inefficiently!
    public static s tring d upChar(char ch, int count){ S tring result = &quot;&quot;; for (int i=0; i<count; i++) result += ch; return result; } Bad practice. Avoid this!
  • 40. 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 r everseIt(String s) { StringBuilder sb = new StringBuilder(); for (int i = s.length()-1; i >= 0; i--) sb.append(s.charAt(i)); return sb.ToString(); }
  • 41. The StringBuilde r Class
    • StringBuilder keeps a buffer memory, allocated in advance
      • Most operations use the buffer memory and do not allocate new objects
    StringBuilder : length() = 11 capacity() = 15 used buffer (length()) unused buffer Capacity H e l l o , J a v a !
  • 42. The StringBuilde r 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
  • 43. The StringBuilde r 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
    • i nsert(int offset , S tring 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
    • t oString() converts the StringBuilder to String object
  • 44. 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(); }
  • 45. 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. a ppend(str1); sb. a ppend(str2); S tring result = sb. t oString();
  • 46. Using StringBuilder Live Demo
  • 47. Formatting Strings Using t oString() and String. f ormat()
  • 48. Method toString()
    • All classes have this public virtual method
      • Returns a human-readable, culture-sensitive string representing the object
      • Most Java Platform types have own implementation of t oString()
  • 49. Method String.format()
    • Applies template s for formatting string s
      • Placeholders are used for dynamic text
      • Like System.out.printf( … )
    String template = &quot;If I were %s, I would %s.&quot;; String sentence1 = String.format( template, &quot;developer&quot;, &quot;know Java&quot;); System.out.println(sentence1); // If I were developer, I would know Java . String sentence2 = String.format( template, &quot;elephant&quot;, &quot;weigh 4500 kg&quot;); System.out.println(sentence2); // If I were elephant, I would weigh 4500 kg.
  • 50. Formatting Dates
    • When we print Dates we use prefix t or T
      • d, e – day (with/without leading zero)
      • m – month
      • y, Y – year (2 or 4 digits)
      • H, M , S – hour, minute, second
    Date now = (new GregorianCalendar()).getTime(); System.out.printf(&quot;Now is &quot; + &quot;%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS&quot;, now ); // Now is 23.05.2006 21:09:32
  • 51. Formatting Strings Live Demo
  • 52. Summary
    • Strings are immutable sequences of chars (instances of java.lang.String )
      • Declared by the class String in Java
      • Can be initialized by string literals
    • The most important string processing members are:
      • length(), charAt() , compare(str1, str2) , indexOf(str) , lastIndexOf(str) , sub s tring(startIndex, endIndex) , replace(oldStr, newStr) , toLower() , toUpper() , trim()
  • 53. Summary (2)
    • Objects can be converted to strings and can be formatted in different styles ( t oString () method)
    • Strings can be constructed by using placeholders and formatting strings ( String. f ormat ( … ) )
  • 54. Exercises
    • Write a program that reads a string, reverses it and prints it on the console. Example: &quot;sample&quot;  &quot; elpmas &quot;.
    • Write a program to check if in a given expression the brackets are put correctly. Example of correct expression: ((a+b)/5-d). Example of incorrect expression: )(a+b)).
  • 55. Exercises (2)
    • Write a program that finds how many times a substring is contained in a given text (perform case insensitive search).
    • Example: The target substring is &quot;in&quot;. The text is as follows:
    • The result is: 9.
    We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
  • 56. Exercises (3)
    • You are given a text. Write a program that changes the text in all regions identified by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested. Example:
    • The expected result:
    We are living in a <upcase> yellow submarine</upcase>. We don't have <upcase>anything</upcase> else . We are living in a YELLOW SUBMARINE . We don't have ANYTHING else.
  • 57. Exercises (4)
    • Write a program that parses an URL address given in the format:
    • and extracts from it the [protocol] , [server] and [resource] elements. For example from the URL http://www.devbg.org/forum/index.php following information should be extracted: [protocol] = &quot; http &quot; , [server] = &quot; www.devbg.org &quot; , [resource] = &quot; /forum/index.php &quot;
    [protocol]://[server]/[resource]
  • 58. Exercises (5)
    • Write a program that extracts from a given text all the sentences that contain given word. Example: The word is &quot;in&quot;. The text is:
    • The expected result is:
    • Consider that the sentences are separated by &quot;.&quot; and the words – by non-letter symbols.
    We are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days. We are living in a yellow submarine. We will move out of it in 5 days.
  • 59. Exercises (6)
    • We are given a string containing a list of forbidden words and a text containing some of these words. Write a program that replaces the forbidden words with asterisks. Example:
    • Words: &quot;Java, JVM, Microsoft&quot;
    • The expected result:
    Microsoft announced its next generation Java compiler today. It uses advanced parser and special optimizer for the Microsoft JVM. ********* announced its next generation **** compiler today. It uses advanced parser and special optimizer for the ********* ***.
  • 60. Exercises (7)
    • Write a prog r am that reads a string from the console and lists all the different letters in the string along with information how many times each letter is found .
    • Write a prog r am that reads a string from the console and lists all the different words in the string with information how many times each word is found.
    • Write a program that reads a string from the console and replace s all series of consecutive identical letters with a single one . E xam p le : &quot;aaaaabbbbbcdddeeeedssaa&quot; -> &quot;abcdedsa&quot; .
  • 61. Exercises (8)
    • Write a program that read s a list of words , separated by spaces (' ') , and print s the list in an alphabetical order.
    • Write a program that lets the user input a string of maximum 20 characters. If the length of the string is less, the rest of the characters should be filled with '*'. Print the string into the console.
  • 62. Exercises (9)
    • * Write a program that encodes and decodes a string using an encryption key (cipher). The key consists of a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or) operation over the first letter of the string with the first of the key, the second – with the second, etc. When the last key character is used, the next is the first.