SlideShare una empresa de Scribd logo
1 de 60
STRINGS AND STRINGS MANIPULATION
CONTENTS
1.   What Is String?
2.   Creating and Using Strings
       •   Declaring, Creating, Reading and Printing
3.   Manipulating Strings
       •   Comparing, Concatenating, Searching, Extracting Substrings, Splitting
4.   Other String Operations
       •   Replacing Substrings, Deleting Substrings, Changing Character Casing,
           Trimming
CONTENTS
5.   Building and Modifying Strings
      •   Using StringBuilder Class
6.   Formatting Strings
WHAT IS STRING?
FREQUENTLY ASKED QUESTIONS FAQ
•   What is string ?
•   Why string is final?
•   What are the ways to declare and initialize the String Object?
•   What is the difference b/w Reference values and literal strings?
•   What is the difference b/w + opretor and concat() method?
•   What is the effect when comparing strings with == and equals() ?
•   What is Difference b/w String class and String Buffer?
•   What is String pool in Java?
•   What does intern() method do in Java?
•   Why String is thread-safe in Java?
•   What is the difference b/w System.out.println(1+2+” text”) and
    System.out.println(” text”+1+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";


         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
•   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.length(); // len = 6
       char ch = s.charAt(1); // ch = 'e„`


                        index =           0    1       2    3   4   5
      s.charAt(index) =                  H     e       l    l   o   !
STRINGS – FIRST EXAMPLE

String s = “Hidaya Institute of Science & Tchnology.";

System.out.printf("s = "%s"%n", s);
System.out.printf("s.length() = %d%n", s.length());

for (int i = 0; i < s.length(); i++) {
  System.out.printf("s[%d] = %c%n", i, s.charAt(i));
}
STRINGS – FIRST EXAMPLE
         Live Demo
Creating and Using Strings

   Declaring, Creating, Reading and Printing
DECLARING STRINGS
•   We use Java String class for declaring string variables:




      String str;
CREATING STRINGS
•   Before initializing a string variable is equal to null
•   Strings can be initialized by:
     • Assigning a string 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

    String s; // s is equal to null
•   Assigning a string literal
    String s = "I am string literal!";
•   Assigning another string variable

    String s2 = s;
•   Assigning the result of string operation

    String s = "I'm " + 42 + " years old.";
READING AND PRINTING STRINGS
•       Reading strings from the console
         • Use the method input.nextLine()

         String s = input.nextLine();

    •      Printng Strings to the console
    •      Use methods print() and println()


         System.out.print("Please enter your name: ");
         String name = input.nextLine();
         System.out.printf("Hello, %s!%n", name);
MANIPULATING STRINGS
Comparing, Concatenating, Searching, Extracting Substrings, Splitting
COMPARING STRINGS
•   There are a number of ways to compare two strings:
     • Dictionary-based string comparison
          • Case-insensitive

    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

          • Case-sensitive

    str1.compareTo(str2);
COMPARING STRINGS (2)
•   Equality checking by equalsIgnoreCase()

     • Performs case-insensitive compare
     • Returns boolean value

     if (str1.equalsIgnoreCase(str2)){
         …
     }

•   The case-sensitive equals() method

      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("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!
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);
COMPARING STRINGS
      Live Demo
CONCATENATING STRINGS
•   There are two ways to combine strings:
     • Using the concat() method

       String str = str1.concat(str2);
     • Using the + or the += operator
       String str = str1 + str2 + str3;
       String str += str1;
•   Any object can be appended to string
       String name = "Peter";
       int age = 22;
       String s = name + " " + age; //  "Peter 22"
CONCATENATING STRINGS – EXAMPLE
 String firstName = "Shahjahan";
 String lastName = "Samoon";

 String fullName = firstName + " " + lastName;

 int age = 23;

 String nameAndAge = "Name: " + fullName +
                     "nAge: " + age;
 System.out.println(nameAndAge);
 // Name: Shahjahan Samoon
 // Age: 23
CONCATENATING STRINGS
        Live Demo
SEARCHING STRINGS
•   Finding a character or substring within given string
     • First occurrence

       indexOf(String str)
     • First occurrence starting at given position

       indexOf(String str, int fromIndex)
     • Last occurrence

       lastIndexOf(String)
     • Last occurrence before given position

       lastIndexOf(String, int fromIndex)
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


          i =   0   1   2   3   4   5   6   7   8   9   10   11   12   …

s.charAt(i) =   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
        String filename = "C:PicsRila2005.jpg";
        String name = filename.substring(8, 16);
        // name is Rila2005
         • str.substring(int beginIndex)
        String filename = "C:PicsSummer2005.jpg";
        String nameAndExtension = filename.substring(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[] split(String regex)
• String regex – String with special format
•   We can list the character which we want to use for separator in square brackets […]

    String[] parts = "Ivan; Petar,Gosho".split("[;,]");
    // this wil separate the stirng into three parts
    // "Ivan", " Petar" and "Gosho"
SPLITTING STRINGS - EXAMPLE
 String listOfBeers =
             "Amstel, Zagorka, Tuborg, Becks.";
 String[] beers = listOfBeers.split("[ ,.]");
 System.out.println("Available beers are:");
 for (String beer : beers) {
       if (!"".equalsIgnoreCase(beer)) {
             System.out.println(beer);
       }
 }
SPLITTING STRINGS
      Live Demo
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 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);

•   Using method toUpperCase()

String alpha = "aBcDeFg";
String upperAlpha = alpha.toUpperCase(); // ABCDEFG
System.out.println(upperAlpha);
TRIMMING WHITE SPACE
•   Using method trim()


    String s = "    example of white space   ";
    String clean = s.trim();
    System.out.println(clean);
OTHER STRING OPERATIONS
         Live Demo
BUILDING AND MODIFYING
       STRINGS
     Using StringBuilder Class
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!
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();
    }
THE STRINGBUILDER CLASS
                                                      Capacity


    StringBuilder: H e                l   l   o   ,    J a v a          !

    length() = 11
    capacity() = 15                       used buffer                          unused
                                          (length())                           buffer


•   StringBuilder keeps a buffer memory, allocated in advance
     • Most operations use the buffer memory and do not allocate new objects
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
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
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:

          String result = str1 + str2;
•   It is equivalent to this code:

          StringBuffer sb = new StringBuffer();
          sb.append(str1);
          sb.append(str2);
          String result = sb.toString();

•   Actually several new objects are created and leaved to the garbage collector
      •     What happens when using + in a loop?
USING STRINGBUILDER
       Live Demo
FORMATTING STRINGS
Using toString() and String.format()
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 toString()
METHOD STRING.FORMAT()
•   Applies templates for formatting strings
     • Placeholders are used for dynamic text
     • Like System.out.printf(…)
    String template = "If I were %s, I would %s.";
    String sentence1 = String.format(
                template, "developer", "know Java");
    System.out.println(sentence1);
    // If I were developer, I would know Java.

    String sentence2 = String.format(
             template, "elephant", "weigh 4500 kg");
    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("Now is " +
      "%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS", now);
// Now is 23.05.2006 21:09:32
FORMATTING STRINGS
       Live Demo
EXERCISES
 Write a program that reads a string, reverses it and prints it on the console. Example:
   "sample"  "elpmas".




 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)).
 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 "in". The text is as follows:



      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.

   The result is: 9.
 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:

      We are living in a <upcase>yellow
      submarine</upcase>. We don't have
      <upcase>anything</upcase> else.


          The expected result:

       We are living in a YELLOW SUBMARINE. We don't
       have ANYTHING else.
 Write a program that parses an URL address given in the format:


      [protocol]://[server]/[resource]

      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] = "http", [server] = "www.devbg.org", [resource] =
      "/forum/index.php "
 Write a program that extracts from a given text all the sentences that contain given word.
   Example: The word is "in". The text is:

       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.


          The expected result is:

       We are living in a yellow submarine.
       We will move out of it in 5 days.

Consider that the sentences are separated by "." and the words – by non-letter symbols.
 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:

       Microsoft announced its next generation Java
       compiler today. It uses advanced parser and
       special optimizer for the Microsoft JVM.

     Words: "Java, JVM, Microsoft"
          The expected result:

       ********* announced its next generation ****
       compiler today. It uses advanced parser and
       special optimizer for the ********* ***.
 Write a program 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 program 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 replaces all series of consecutive
    identical letters with a single one. Example: "aaaaabbbbbcdddeeeedssaa" -> "abcdedsa".
 Write a program that reads a list of words, separated by spaces (' ') , and prints 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.

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Java String
Java String Java String
Java String
 
Strings in c++
Strings in c++Strings in c++
Strings in c++
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Data types in python
Data types in pythonData types in python
Data types in python
 
String functions in C
String functions in CString functions in C
String functions in C
 
Templates in c++
Templates in c++Templates in c++
Templates in c++
 
Strings in java
Strings in javaStrings in java
Strings in java
 
Strings
StringsStrings
Strings
 
Introduction to c++ ppt
Introduction to c++ pptIntroduction to c++ ppt
Introduction to c++ ppt
 
What is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | EdurekaWhat is Python Lambda Function? Python Tutorial | Edureka
What is Python Lambda Function? Python Tutorial | Edureka
 
standard template library(STL) in C++
standard template library(STL) in C++standard template library(STL) in C++
standard template library(STL) in C++
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Input processing and output in Python
Input processing and output in PythonInput processing and output in Python
Input processing and output in Python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
 
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)Hashing notes data structures (HASHING AND HASH FUNCTIONS)
Hashing notes data structures (HASHING AND HASH FUNCTIONS)
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
structure and union
structure and unionstructure and union
structure and union
 
StringTokenizer in java
StringTokenizer in javaStringTokenizer in java
StringTokenizer in java
 

Destacado

Java packages and access specifiers
Java packages and access specifiersJava packages and access specifiers
Java packages and access specifiersashishspace
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaCPD INDIA
 

Destacado (7)

Java Programming - 05 access control in java
Java Programming - 05 access control in javaJava Programming - 05 access control in java
Java Programming - 05 access control in java
 
Oops (inheritance&interface)
Oops (inheritance&interface)Oops (inheritance&interface)
Oops (inheritance&interface)
 
Lecture09
Lecture09Lecture09
Lecture09
 
Java packages and access specifiers
Java packages and access specifiersJava packages and access specifiers
Java packages and access specifiers
 
[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers[OOP - Lec 07] Access Specifiers
[OOP - Lec 07] Access Specifiers
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
oops concept in java | object oriented programming in java
oops concept in java | object oriented programming in javaoops concept in java | object oriented programming in java
oops concept in java | object oriented programming in java
 

Similar a Java Strings Guide

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdfssusere19c741
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text ProcessingIntro C# Book
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanKavita Ganesan
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20myrajendra
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processingmaznabili
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packagesSardar Alam
 
String and string buffer
String and string bufferString and string buffer
String and string bufferkamal kotecha
 
Text processing
Text processingText processing
Text processingIcancode
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTSasideepa
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTSasideepa
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programmingAppili Vamsi Krishna
 

Similar a Java Strings Guide (20)

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
Java string handling
Java string handlingJava string handling
Java string handling
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Strings v.1.1
Strings v.1.1Strings v.1.1
Strings v.1.1
 
0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf0-Slot21-22-Strings.pdf
0-Slot21-22-Strings.pdf
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Java String Handling
Java String HandlingJava String Handling
Java String Handling
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita GanesanIntroduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
 
String slide
String slideString slide
String slide
 
String classes and its methods.20
String classes and its methods.20String classes and its methods.20
String classes and its methods.20
 
13 Strings and text processing
13 Strings and text processing13 Strings and text processing
13 Strings and text processing
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Text processing
Text processingText processing
Text processing
 
CPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPTCPSTRINGSARGAVISTRINGS.PPT
CPSTRINGSARGAVISTRINGS.PPT
 
BHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPTBHARGAVISTRINGS.PPT
BHARGAVISTRINGS.PPT
 
Handling of character strings C programming
Handling of character strings C programmingHandling of character strings C programming
Handling of character strings C programming
 
M C6java7
M C6java7M C6java7
M C6java7
 
Quick swift tour
Quick swift tourQuick swift tour
Quick swift tour
 

Último

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Último (20)

Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Java Strings Guide

  • 1.
  • 2. STRINGS AND STRINGS MANIPULATION
  • 3. CONTENTS 1. What Is String? 2. Creating and Using Strings • Declaring, Creating, Reading and Printing 3. Manipulating Strings • Comparing, Concatenating, Searching, Extracting Substrings, Splitting 4. Other String Operations • Replacing Substrings, Deleting Substrings, Changing Character Casing, Trimming
  • 4. CONTENTS 5. Building and Modifying Strings • Using StringBuilder Class 6. Formatting Strings
  • 6. FREQUENTLY ASKED QUESTIONS FAQ • What is string ? • Why string is final? • What are the ways to declare and initialize the String Object? • What is the difference b/w Reference values and literal strings? • What is the difference b/w + opretor and concat() method? • What is the effect when comparing strings with == and equals() ? • What is Difference b/w String class and String Buffer? • What is String pool in Java? • What does intern() method do in Java? • Why String is thread-safe in Java? • What is the difference b/w System.out.println(1+2+” text”) and System.out.println(” text”+1+2) ?
  • 7. 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
  • 8. 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
  • 9. JAVA.LANG.STRING • 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.length(); // len = 6 char ch = s.charAt(1); // ch = 'e„` index = 0 1 2 3 4 5 s.charAt(index) = H e l l o !
  • 10. STRINGS – FIRST EXAMPLE String s = “Hidaya Institute of Science & Tchnology."; System.out.printf("s = "%s"%n", s); System.out.printf("s.length() = %d%n", s.length()); for (int i = 0; i < s.length(); i++) { System.out.printf("s[%d] = %c%n", i, s.charAt(i)); }
  • 11. STRINGS – FIRST EXAMPLE Live Demo
  • 12. Creating and Using Strings Declaring, Creating, Reading and Printing
  • 13. DECLARING STRINGS • We use Java String class for declaring string variables: String str;
  • 14. CREATING STRINGS • Before initializing a string variable is equal to null • Strings can be initialized by: • Assigning a string literal to the string variable • Assigning the value of another string variable • Assigning the result of operation of type string
  • 15. CREATING STRINGS (2) • Not initialized variables has value of null String s; // s is equal to null • Assigning a string literal String s = "I am string literal!"; • Assigning another string variable String s2 = s; • Assigning the result of string operation String s = "I'm " + 42 + " years old.";
  • 16. READING AND PRINTING STRINGS • Reading strings from the console • Use the method input.nextLine() String s = input.nextLine(); • Printng Strings to the console • Use methods print() and println() System.out.print("Please enter your name: "); String name = input.nextLine(); System.out.printf("Hello, %s!%n", name);
  • 17. MANIPULATING STRINGS Comparing, Concatenating, Searching, Extracting Substrings, Splitting
  • 18. COMPARING STRINGS • There are a number of ways to compare two strings: • Dictionary-based string comparison • Case-insensitive 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 • Case-sensitive str1.compareTo(str2);
  • 19. COMPARING STRINGS (2) • Equality checking by equalsIgnoreCase() • Performs case-insensitive compare • Returns boolean value if (str1.equalsIgnoreCase(str2)){ … } • The case-sensitive equals() method if (str1.equals(str2)){ … }
  • 20. 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("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!
  • 21. 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);
  • 22. COMPARING STRINGS Live Demo
  • 23. CONCATENATING STRINGS • There are two ways to combine strings: • Using the concat() method String str = str1.concat(str2); • Using the + or the += operator String str = str1 + str2 + str3; String str += str1; • Any object can be appended to string String name = "Peter"; int age = 22; String s = name + " " + age; //  "Peter 22"
  • 24. CONCATENATING STRINGS – EXAMPLE String firstName = "Shahjahan"; String lastName = "Samoon"; String fullName = firstName + " " + lastName; int age = 23; String nameAndAge = "Name: " + fullName + "nAge: " + age; System.out.println(nameAndAge); // Name: Shahjahan Samoon // Age: 23
  • 26. SEARCHING STRINGS • Finding a character or substring within given string • First occurrence indexOf(String str) • First occurrence starting at given position indexOf(String str, int fromIndex) • Last occurrence lastIndexOf(String) • Last occurrence before given position lastIndexOf(String, int fromIndex)
  • 27. 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 i = 0 1 2 3 4 5 6 7 8 9 10 11 12 … s.charAt(i) = J a v a P r o g r a m m …
  • 28. SEARCHING STRINGS Live Demo
  • 29. EXTRACTING SUBSTRINGS • Extracting substrings • str.substring(int beginIndex, int endIndex) • lastIndex is not included String filename = "C:PicsRila2005.jpg"; String name = filename.substring(8, 16); // name is Rila2005 • str.substring(int beginIndex) String filename = "C:PicsSummer2005.jpg"; String nameAndExtension = filename.substring(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
  • 31. SPLITTING STRINGS • To split a string by given separator(s) use the following method: String[] split(String regex) • String regex – String with special format • We can list the character which we want to use for separator in square brackets […] String[] parts = "Ivan; Petar,Gosho".split("[;,]"); // this wil separate the stirng into three parts // "Ivan", " Petar" and "Gosho"
  • 32. SPLITTING STRINGS - EXAMPLE String listOfBeers = "Amstel, Zagorka, Tuborg, Becks."; String[] beers = listOfBeers.split("[ ,.]"); System.out.println("Available beers are:"); for (String beer : beers) { if (!"".equalsIgnoreCase(beer)) { System.out.println(beer); } }
  • 33. SPLITTING STRINGS Live Demo
  • 34. OTHER STRING OPERATIONS Replacing Substrings, Changing Character Casing, Trimming
  • 35. 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
  • 36. CHANGING CHARACTER CASING • Using method toLowerCase() String alpha = "aBcDeFg"; String lowerAlpha = alpha.toLowerCase(); // abcdefg System.out.println(lowerAlpha); • Using method toUpperCase() String alpha = "aBcDeFg"; String upperAlpha = alpha.toUpperCase(); // ABCDEFG System.out.println(upperAlpha);
  • 37. TRIMMING WHITE SPACE • Using method trim() String s = " example of white space "; String clean = s.trim(); System.out.println(clean);
  • 39. BUILDING AND MODIFYING STRINGS Using StringBuilder Class
  • 40. 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!
  • 41. 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(); }
  • 42. THE STRINGBUILDER CLASS Capacity StringBuilder: H e l l o , J a v a ! length() = 11 capacity() = 15 used buffer unused (length()) buffer • StringBuilder keeps a buffer memory, allocated in advance • Most operations use the buffer memory and do not allocate new objects
  • 43. 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
  • 44. 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
  • 45. 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(); }
  • 46. HOW THE + OPERATOR DOES STRING CONCATENATIONS? • Consider following string concatenation: String result = str1 + str2; • It is equivalent to this code: StringBuffer sb = new StringBuffer(); sb.append(str1); sb.append(str2); String result = sb.toString(); • Actually several new objects are created and leaved to the garbage collector • What happens when using + in a loop?
  • 47. USING STRINGBUILDER Live Demo
  • 48. FORMATTING STRINGS Using toString() and String.format()
  • 49. 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 toString()
  • 50. METHOD STRING.FORMAT() • Applies templates for formatting strings • Placeholders are used for dynamic text • Like System.out.printf(…) String template = "If I were %s, I would %s."; String sentence1 = String.format( template, "developer", "know Java"); System.out.println(sentence1); // If I were developer, I would know Java. String sentence2 = String.format( template, "elephant", "weigh 4500 kg"); System.out.println(sentence2); // If I were elephant, I would weigh 4500 kg.
  • 51. 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("Now is " + "%1$td.%1$tm.%1$tY %1$tH:%1$tM:%1$tS", now); // Now is 23.05.2006 21:09:32
  • 52. FORMATTING STRINGS Live Demo
  • 53. EXERCISES  Write a program that reads a string, reverses it and prints it on the console. Example: "sample"  "elpmas".  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)).
  • 54.  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 "in". The text is as follows: 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. The result is: 9.
  • 55.  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: We are living in a <upcase>yellow submarine</upcase>. We don't have <upcase>anything</upcase> else. The expected result: We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.
  • 56.  Write a program that parses an URL address given in the format: [protocol]://[server]/[resource] 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] = "http", [server] = "www.devbg.org", [resource] = "/forum/index.php "
  • 57.  Write a program that extracts from a given text all the sentences that contain given word. Example: The word is "in". The text is: 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. The expected result is: We are living in a yellow submarine. We will move out of it in 5 days. Consider that the sentences are separated by "." and the words – by non-letter symbols.
  • 58.  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: Microsoft announced its next generation Java compiler today. It uses advanced parser and special optimizer for the Microsoft JVM. Words: "Java, JVM, Microsoft" The expected result: ********* announced its next generation **** compiler today. It uses advanced parser and special optimizer for the ********* ***.
  • 59.  Write a program 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 program 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 replaces all series of consecutive identical letters with a single one. Example: "aaaaabbbbbcdddeeeedssaa" -> "abcdedsa".
  • 60.  Write a program that reads a list of words, separated by spaces (' ') , and prints 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.