Presentation is loading. Please wait.

Presentation is loading. Please wait.

Strings and Text Processing

Similar presentations


Presentation on theme: "Strings and Text Processing"— Presentation transcript:

1 Strings and Text Processing
Processing and Manipulating Text Advanced Java SoftUni Team Technical Trainers Software University © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

2 Table of Contents What is a String? Manipulating Strings
Comparing, Concatenating, Searching Extracting Substrings, Splitting © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

3 Table of Contents (2) Other String Operators
Replacing Substrings, Deleting Substrings Changing Character Casing, Trimming Building and Modifying Strings Why the + Operator is Slow? Using the StringBuilder Class © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

4 Questions sli.do #0752

5 What is a String? Strings are represented by java.lang.String objects in Java String objects contain an immutable (read-only) sequence of characters Before initializing, a String variable has null value

6 Comparing, Concatenating, Searching, Extracting Substrings, Splitting
* Manipulating Strings Comparing, Concatenating, Searching, Extracting Substrings, Splitting (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

7 Comparing Strings Several ways to compare two Strings:
Dictionary-based String comparison Case-insensitive Case-sensitive int result = str1.compareToIgnoreCase(str2); // result == 0 if str1 equals str2 // result < 0 if str1 is before str2 // result > 0 if str1 is after str2 int result = str1.compareTo(str2);

8 Comparing Strings (2) Equality checking by operator ==
WARNING! Compares reference and not the content of the String Using the equals() and equalsIgnoreCase() method Unlike the operator == these methods compare Strings by their value if (str1 == str2) { } if (str1.equals(str2)) { }

9 Comparing Strings Live demo
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

10 Concatenating Strings
There are two ways to combine Strings: Using the concat() method Using the + or the += operators Any object can be appended to a String String str = str.concat(strToConcat); String str = str1 + str2 + str3; String str += str1; String name = "Peter"; int age = 22; String s = name + " " + age; //  "Peter 22"

11 Concatenating Strings
Live demo © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

12 Searching in Strings Finding a character or substring within given string str.indexOf(String/char term) – returns the index of the first occurrence of term in str Returns -1 if there is no match str.lastIndexOf(String/char term) – returns the index of the last occurrence of term in str String = int firstIndex = // 5 int noIndex = 6); // -1 string verse = "To be or not to be.."; int lastIndex = verse.lastIndexOf("be"); // 16

13 Searching in Strings Live demo
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

14 Extracting Substrings
str.substring(int startIndex, int endIndex) str.substring(int startIndex) String filename = "C:\\Pics\\Rila2005.jpg"; String name = filename.substring(8, 16); // name is Rila2005 String filename = "C:\\Pics\\Summer2009.jpg"; String nameAndExtension = filename.substring(8); // nameAndExtension is Summer2009.jpg 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 l a . j p g

15 Extracting Substrings
Live demo © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

16 Splitting Strings To split a string by given separator(s) use the following method: Example: String[] split(String regex) String listOfBeers = "Shumensko, Stolichno, Staropramen"; String[] beers = listOfBeers.split(", "); System.out.println("Available beers are:"); for (String beer : beers) { System.out.println(beer); }

17 Splitting Strings Live demo
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

18 Other String Operations
* Other String Operations Replacing Substrings, Changing Character Casing, Trimming and boolean methods (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

19 Replacing substrings str.replace(CharSequence tar, CharSequence rep) – replaces all occurrences of given String with another The result is a new string (strings are immutable) str.replaceAll(String regex, String rep) – replaces all matches of given regex with a specified String String cocktail = "Vodka + Martini + Cherry"; String replaced = cocktail.replace("+", "and"); // Vodka and Martini and Cherry

20 Changing Character Casing
Using the method toLowerCase() Using the method toUpperCase() String alpha = "aBcDeFg"; String lowerAlpha = alpha.toLowerCase(); // abcdefg System.out.println(lowerAlpha); String alpha = "aBcDeFg"; String upperAlpha = alpha.toUpperCase(); // ABCDEFG System.out.println(upperAlpha);

21 Trimming White Space and boolean methods
str.trim() – trims whitespaces at start and end of string str.startsWith(String prefix) str.endsWith(String suffix) String s = " example of white space "; String clean = s.trim(); System.out.println(clean); // "example of white space" String s = "C# is the best!"; boolean isItThough = s.startsWith(“Java"); System.out.println(isQuestion); // false String s = "How are you?"; boolean isQuestion = s.endsWith("?"); System.out.println(isQuestion); // true

22 Other String Operations
Live demo

23 Building and Modifying Strings
Using the StringBuilder Class

24 StringBuilder: How It Works?
Capacity StringBuilder: length() = 9 capacity() = 25 Y o , J a v ! used buffer (Length) unused buffer StringBuilder keeps a buffer memory, allocated in advance Most operations use the buffer memory and do not allocate new objects

25 Changing the Contents of a String
* Changing the Contents of a String Use the java.lang.StringBuilder class for modifiable Strings of characters: Use StringBuilder if you need to keep adding characters to a String or when you have to print to the console many times public static String reverseString(String s) { StringBuilder sb = new StringBuilder(); for (int i = s.length() - 1; i >= 0; i--) { sb.append(s.charAt(i)); } return sb.toString(); } 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. (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

26 The StringBuilder Class
StringBuilder(int capacity) constructor allocates in advance size of buffer capacity capacity() holds the currently allocated space (in characters) charAt(int i) gives access to the char value at given position length() holds the length of the String in the buffer setLength(int newLength) sets the length of the character sequence if the new one is greater, \0 chars are added if not the method acts as a reverse substring

27 The StringBuilder Class (2)
append(…) appends an object after the last character in the buffer delete(int startIndex, int endIndex) removes the characters in a substring of this sequence. insert(int index, CharSequence str, int start, int end) inserts a subsequence of the specified CharSequence into this sequence. replace(int start, int end, String str) replaces the characters in a substring of this sequence with characters in the specified String toString() converts the StringBuilder to String

28 Using StringBuilder Live demo

29 Summary Strings are immutable sequences of
* Summary Strings are immutable sequences of chars (instances of java.lang.String) Can’t be iterated Support operations such as substring(), indexOf(), trim(), etc. Changes to the String create a new object, instead of modifying the old one StringBuilder offers good performance Recommended when concatenating Strings in a loop (c) 2007 National Academy for Software Development - All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*

30 Strings and Text Processing
© Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

31 License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license Attribution: this work may contain portions from "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license "C# Part I" course by Telerik Academy under CC-BY-NC-SA license "C# Part II" course by Telerik Academy under CC-BY-NC-SA license © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

32 Free Trainings @ Software University
Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software Facebook facebook.com/SoftwareUniversity Software YouTube youtube.com/SoftwareUniversity Software University Forums – forum.softuni.bg © Software University Foundation – This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.


Download ppt "Strings and Text Processing"

Similar presentations


Ads by Google