Strings and Strings Manipulation
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
Contents (2) Building and Modifying Strings Using  StringBuilder  Class Formatting Strings
What Is String?
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
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
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 !
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)); }
Strings – First Example Live Demo
Declaring, Creating, Reading and Printing Creating and Using Strings
Declaring Strings We use Java String class for declaring string variables: String str;
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
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;;
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);
Live Demo Reading and Printing Strings
Manipulating Strings Comparing, Concatenating, Searching, Extracting Substrings, Splitting
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);
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)){ … }
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 !
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);
Comparing Strings Live Demo
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;
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
Concatenating Strings Live Demo
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)
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 …
Searching Strings Live Demo
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
Extracting Substrings Live Demo
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;
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); } }
Splitting Strings Live Demo
Other String Operations Replacing Substrings, Changing Character Casing, Trimming
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
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);
Trimming White Space Using method  trim() String s = &quot;  example of white space  &quot;; String clean = s.trim(); System.out.println(clean);
Other String Operations Live Demo
Building and Modifying Strings Using  StringBuilder  C lass
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!
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(); }
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 !
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
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
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(); }
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();
Using  StringBuilder Live Demo
Formatting Strings Using  t oString()  and  String. f ormat()
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()
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.
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
Formatting Strings Live Demo
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()
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 ( … ) )
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)).
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.
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.
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]
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.
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 ********* ***.
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; .
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.
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.

Strings v.1.1

  • 1.
    Strings and StringsManipulation
  • 2.
    Contents What IsString? 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) Buildingand Modifying Strings Using StringBuilder Class Formatting Strings
  • 4.
  • 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 = &quot;Hello, Java&quot;; 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 = &quot;Hello!&quot;; 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 – FirstExample 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 – FirstExample Live Demo
  • 10.
    Declaring, Creating, Readingand Printing Creating and Using Strings
  • 11.
    Declaring Strings Weuse Java String class for declaring string variables: String str;
  • 12.
    Creating Strings Before 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 PrintingStrings 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 Readingand Printing Strings
  • 16.
    Manipulating Strings Comparing,Concatenating, Searching, Extracting Substrings, Splitting
  • 17.
    Comparing Strings Thereare 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.
  • 22.
    Concatenating Strings Thereare 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.
  • 25.
    Searching Strings Find 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.
  • 28.
    Extracting Substrings Extractingsubstrings 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.
  • 30.
    Splitting Strings Tosplit 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.
  • 33.
    Other String OperationsReplacing Substrings, Changing Character Casing, Trimming
  • 34.
    Replacing Substrings replace( 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 CasingUsing 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 SpaceUsing method trim() String s = &quot; example of white space &quot;; String clean = s.trim(); System.out.println(clean);
  • 37.
  • 38.
    Building and ModifyingStrings Using StringBuilder C lass
  • 39.
    Constructing Strings Stringsare 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 Contentsof 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 StringBuilder 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 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
  • 43.
    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 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.
  • 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 Whenwe 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.
  • 52.
    Summary Strings areimmutable 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) Objectscan 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 aprogram 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) Writea 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) Youare 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) Writea 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) Writea 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) Weare 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) Writea 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.

Editor's Notes

  • #2 * 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.* ##
  • #3 * 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.* ##
  • #4 * 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.* ##
  • #5 * 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.* ##
  • #10 * 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.* ##
  • #11 * 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.* ##
  • #16 * 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.* ##
  • #17 * 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.* ##
  • #22 * 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.* ##
  • #25 * 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.* ##
  • #28 * 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.* ##
  • #30 * 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.* ##
  • #33 * 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.* ##
  • #34 * 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.* ##
  • #38 * 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.* ##
  • #41 * 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 = &amp;quot;Fasten your seatbelts, &amp;quot;; quote = quote + &amp;quot;it’s going to be a bumpy night.&amp;quot;; 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(&amp;quot;Fasten your seatbelts, &amp;quot;); quote.append(&amp;quot; it’s going to be a bumpy night. &amp;quot;); 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 .
  • #48 * 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.* ##
  • #52 * 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.* ##
  • #53 * 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.* ##
  • #54 * 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.* ##
  • #55 * 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.* ##
  • #58 * 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.* ##
  • #61 * 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.* ##
  • #63 * 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.* ##