SlideShare a Scribd company logo
1 of 39
Text Processing
Software University
http://softuni.bg
SoftUni Team
Technical Trainers
1
Manipulating Text
sli.do
#fund-java
Questions?
2
Table of Contents
1. What Is a String?
2. Manipulating Strings
3. Building and Modifying Strings
 Using StringBuilder Class
 Why Concatenation Is a Slow Operation?
3
Strings
What Is a String?
 Strings are sequences of characters (texts)
 The string data type in Java
 Declared by the String
 Strings are enclosed in double quotes:
What Is a String?
5
String text = "Hello, Java";
 Strings are immutable (read-only)
sequences of characters
 Accessible by index (read-only)
 Strings use Unicode
(can use most alphabets, e.g. Arabic)
Strings Are Immutable
6
String str = "Hello, Java";
char ch = str.charAt(2); // l
String greeting = "你好"; // (lí-hó) Taiwanese
 Initializing from a string literal:
 Reading a string from the console:
 Converting a string from and to a char array:
Initializing a String
7
String str = "Hello, Java";
String name = sc.nextLine();
System.out.println("Hi, " + name);
String str = new String(new char[] {'s', 't', 'r'});
char[] charArr = str.toCharArray();
// ['s', 't', 'r']
Manipulating Strings
Concatenating
 Use the + or the += operators
 Use the concat() method
String greet = "Hello, ";
String name = "John";
String result = greet.concat(name);
System.out.println(result); // "Hello, John"
String text = "Hello, ";
text += "John"; // "Hello, John"
String text = "Hello" + ", " + "world!";
// "Hello, world!"
8
Joining Strings
 String.join("", …) concatenates strings
 Or an array/list of strings
 Useful for repeating a string
10
String t = String.join("", "con", "ca", "ten", "ate");
// "concatenate"
String s = "abc";
String[] arr = new String[3];
for (int i = 0; i < arr.length; i++) { arr[i] = s; }
String repeated = String.join("", arr); // "abcabcabc"
 Read an array from strings
 Repeat each word n times, where n is the length of the word
Problem: Repeat Strings
11
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
hi abc add hihiabcabcabcaddaddadd
work workworkworkwork
ball ballballballball
Solution: Repeat Strings (1)
12
String[] words = sc.nextLine().split(" ");
List<String> result = new ArrayList<>();
for (String word : words) {
result.add(repeat(word, word.length()));
}
System.out.println(String.join("", result));
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
static String repeat(String s, int repeatCount) {
String[] repeatArr = new String[repeatCount];
for (int i = 0; i < repeatCount; i++) {
repeatArr[i] = s;
}
return String.join("", repeatArr);
}
Solution: Repeat Strings (2)
13
Substring
 substring(int startIndex, int endIndex)
 substring(int startIndex)
14
String text = "My name is John";
String extractWord = text.substring(11);
System.out.println(extractWord); // John
String card = "10C";
String power = card.substring(0, 2);
System.out.println(power); // 10
Searching (1)
 indexOf() - returns the first match index or -1
 lastIndexOf() - finds the last occurrence
15
String fruits = "banana, apple, kiwi, banana, apple";
System.out.println(fruits.lastIndexOf("banana")); // 21
System.out.println(fruits.lastIndexOf("orange")); // -1
String fruits = "banana, apple, kiwi, banana, apple";
System.out.println(fruits.indexOf("banana")); // 0
System.out.println(fruits.indexOf("orange")); // -1
Searching (2)
 contains() - checks whether one string
contains another
16
String text = "I love fruits.";
System.out.println(text.contains("fruits"));
// true
System.out.println(text.contains("banana"));
// false
Problem: Substring
17
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
 You are given a remove word and a text
 Remove all substrings that are equal to the remove word
ice
kicegiceiceb
kgb
abc
tabctqw
ttqw
key
keytextkey
text
word
wordawordbwordc
abc
Solution: Substring
18
String key = sc.nextLine();
String text = sc.nextLine();
int index = text.indexOf(key);
while (index != -1) {
text = text.replace(key, "");
index = text.indexOf(key);
}
System.out.println(text);
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
Splitting
 Split a string by given pattern
 Split by multiple separators
19
String text = "Hello, I am John.";
String[] words = text.split("[, .]+");
// "Hello", "I", "am", "John"
String text = "Hello, john@softuni.bg, you have been
using john@softuni.bg in your registration";
String[] words = text.split(", ");
// words[]: "Hello", "john@softuni.bg","you have been…"
Replacing
 replace(match, replacement) - replaces all
occurrences
 The result is a new string (strings are immutable)
20
String text = "Hello, john@softuni.bg, you have been
using john@softuni.bg in your registration.";
String replacedText = text
.replace("john@softuni.bg", "john@softuni.com");
System.out.println(replacedText);
// Hello, john@softuni.com, you have been using
john@softuni.com in your registration.
Problem: Text Filter
21
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
 You are given a string of banned words and a text
 Replace all banned words in the text with asterisks (*)
Linux, Windows
It is not Linux, it is GNU/Linux. Linux is merely the
kernel, while GNU adds the functionality...
It is not *****, it is GNU/*****. ***** is merely
the kernel, while GNU adds the functionality...
Solution: Text Filter (1)
22
String[] banWords = sc.nextLine.split(", ");
String text = sc.nextLine();
for (String banWord : banWords) {
if (text.contains(banWord)) {
String replacement = repeatStr("*",
banWord.length());
text = text.replace(banWord, replacement);
}
}
System.out.println(text);
contains(…) checks if string
contains another string
replace() a word with a sequence
of asterisks of the same length
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
Solution: Text Filter (2)
23
private static String repeatStr(String str, int length) {
String replacement = "";
for (int i = 0; i < length; i++) {
replacement += str;
}
return replacement;
}
Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
Live Exercises
Building and Modifying Strings
Using the StringBuilder Class
 StringBuilder keeps a buffer space, allocated in advance
 Do not allocate memory for
most operations  performance
StringBuilder: How It Works?
H e l l o , J A V AStringBuilder:
length() = 10
capacity() = 16
Capacity
used buffer
(Length)
unused
buffer
24
Using StringBuilder Class
 Use the StringBuilder to build/modify strings
27
StringBuilder sb = new StringBuilder();
sb.append("Hello, ");
sb.append("John! ");
sb.append("I sent you an email.");
System.out.println(sb.toString());
// Hello, John! I sent you an email.
Concatenation vs. StringBuilder (1)
 Concatenating strings is a slow operation
because each iteration creates a new string
28
Tue Jul 10 13:57:20 EEST 2018
Tue Jul 10 13:58:07 EEST 2018
System.out.println(new Date());
String text = "";
for (int i = 0; i < 1000000; i++)
text += "a";
System.out.println(new Date());
Concatenation vs. StringBuilder (2)
 Using StringBuilder
29
Tue Jul 10 14:51:31 EEST 2018
Tue Jul 10 14:51:31 EEST 2018
System.out.println(new Date());
StringBuilder text = new
StringBuilder();
for (int i = 0; i < 1000000; i++)
text.append("a");
System.out.println(new Date());
StringBuilder Methods (1)
 append() - appends the string representation
of the argument
 length() - holds the length of the string in the buffer
 setLength(0) - removes all characters
30
StringBuilder sb = new StringBuilder();
sb.append("Hello Peter, how are you?");
sb.append("Hello Peter, how are you?");
System.out.println(sb.length()); // 25
StringBuilder Methods (2)
 charAt(int index) - returns char on index
 insert(int index, String str) –
inserts a string at the specified character position
31
StringBuilder sb = new StringBuilder();
sb.append("Hello Peter, how are you?");
System.out.println(sb.charAt(1)); // e
sb.insert(11, " Ivanov");
System.out.println(sb);
// Hello Peter Ivanov, how are you?
StringBuilder Methods (3)
 replace(int startIndex, int endIndex,
String str) - replaces the chars in a substring
 toString() - converts the value of this instance
to a String
32
String text = sb.toString();
System.out.println(text);
// Hello George, how are you?
sb.append("Hello Peter, how are you?");
sb.replace(6, 11, "George");
Live Exercises
 …
 …
 …
Summary
34
 Strings are immutable sequences of
Unicode characters
 String processing methods
 concat(), indexOf(), contains(),
substring(), split(), replace(), …
 StringBuilder efficiently builds/modifies
strings
 https://softuni.bg/courses/programming-fundamentals
SoftUni Diamond Partners
SoftUni Organizational Partners
 Software University – High-Quality Education and
Employment Opportunities
 softuni.bg
 Software University Foundation
 http://softuni.foundation/
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums
 forum.softuni.bg
Trainings @ Software University (SoftUni)
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-NonCom
mercial-ShareAlike 4.0 International" license
License
39

More Related Content

What's hot

05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and SetIntro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queuesIntro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm ComplexityIntro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstractionIntro C# Book
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingSvetlin Nakov
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and VariablesIntro C# Book
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: ArraysSvetlin Nakov
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsSvetlin Nakov
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Svetlin Nakov
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionSvetlin Nakov
 

What's hot (20)

05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set18. Dictionaries, Hash-Tables and Set
18. Dictionaries, Hash-Tables and Set
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...03 and 04 .Operators, Expressions, working with the console and conditional s...
03 and 04 .Operators, Expressions, working with the console and conditional s...
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
06.Loops
06.Loops06.Loops
06.Loops
 
09. Methods
09. Methods09. Methods
09. Methods
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 
Java Foundations: Strings and Text Processing
Java Foundations: Strings and Text ProcessingJava Foundations: Strings and Text Processing
Java Foundations: Strings and Text Processing
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
Chapter 2 Java Methods
Chapter 2 Java MethodsChapter 2 Java Methods
Chapter 2 Java Methods
 
Java Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, LoopsJava Foundations: Basic Syntax, Conditions, Loops
Java Foundations: Basic Syntax, Conditions, Loops
 
Chapter 4 - Classes in Java
Chapter 4 - Classes in JavaChapter 4 - Classes in Java
Chapter 4 - Classes in Java
 
Java Basics - Part1
Java Basics - Part1Java Basics - Part1
Java Basics - Part1
 
Chapter 3 Arrays in Java
Chapter 3 Arrays in JavaChapter 3 Arrays in Java
Chapter 3 Arrays in Java
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Java Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type ConversionJava Foundations: Data Types and Type Conversion
Java Foundations: Data Types and Type Conversion
 

Similar to 13. Java text processing

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
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic SyntaxAdil Jafri
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)Tak Lee
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
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
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossumoscon2007
 
Learn VbScript -String Functions
Learn VbScript -String FunctionsLearn VbScript -String Functions
Learn VbScript -String FunctionsNilanjan Saha
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 featuresindia_mani
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimizedWoody Pewitt
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUadAccount
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdfAnanthi68
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
How many lexemes does the following Java code containGive the num.pdf
How many lexemes does the following Java code containGive the num.pdfHow many lexemes does the following Java code containGive the num.pdf
How many lexemes does the following Java code containGive the num.pdffeelingcomputors
 

Similar to 13. Java text processing (20)

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
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
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
 
Os Vanrossum
Os VanrossumOs Vanrossum
Os Vanrossum
 
Learn VbScript -String Functions
Learn VbScript -String FunctionsLearn VbScript -String Functions
Learn VbScript -String Functions
 
JDK1.7 features
JDK1.7 featuresJDK1.7 features
JDK1.7 features
 
Is your C# optimized
Is your C# optimizedIs your C# optimized
Is your C# optimized
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
How many lexemes does the following Java code containGive the num.pdf
How many lexemes does the following Java code containGive the num.pdfHow many lexemes does the following Java code containGive the num.pdf
How many lexemes does the following Java code containGive the num.pdf
 

More from Intro C# Book

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversalIntro C# Book
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving Intro C# Book
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming CodeIntro C# Book
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism Intro C# Book
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstractionIntro C# Book
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulationIntro C# Book
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritanceIntro C# Book
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arraysIntro C# Book
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classesIntro C# Book
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handlingIntro C# Book
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classesIntro C# Book
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with javaIntro C# Book
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem SolvingIntro C# Book
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming CodeIntro C# Book
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like StructuresIntro C# Book
 

More from Intro C# Book (16)

17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal17. Java data structures trees representation and traversal
17. Java data structures trees representation and traversal
 
Java Problem solving
Java Problem solving Java Problem solving
Java Problem solving
 
21. Java High Quality Programming Code
21. Java High Quality Programming Code21. Java High Quality Programming Code
21. Java High Quality Programming Code
 
20.5 Java polymorphism
20.5 Java polymorphism 20.5 Java polymorphism
20.5 Java polymorphism
 
20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction20.4 Java interfaces and abstraction
20.4 Java interfaces and abstraction
 
20.3 Java encapsulation
20.3 Java encapsulation20.3 Java encapsulation
20.3 Java encapsulation
 
20.2 Java inheritance
20.2 Java inheritance20.2 Java inheritance
20.2 Java inheritance
 
18. Java associative arrays
18. Java associative arrays18. Java associative arrays
18. Java associative arrays
 
14. Java defining classes
14. Java defining classes14. Java defining classes
14. Java defining classes
 
12. Java Exceptions and error handling
12. Java Exceptions and error handling12. Java Exceptions and error handling
12. Java Exceptions and error handling
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
01. Introduction to programming with java
01. Introduction to programming with java01. Introduction to programming with java
01. Introduction to programming with java
 
23. Methodology of Problem Solving
23. Methodology of Problem Solving23. Methodology of Problem Solving
23. Methodology of Problem Solving
 
21. High-Quality Programming Code
21. High-Quality Programming Code21. High-Quality Programming Code
21. High-Quality Programming Code
 
17. Trees and Tree Like Structures
17. Trees and Tree Like Structures17. Trees and Tree Like Structures
17. Trees and Tree Like Structures
 
14 Defining Classes
14 Defining Classes14 Defining Classes
14 Defining Classes
 

Recently uploaded

Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Sonam Pathan
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一Fs
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一3sw2qly1
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Dana Luther
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012rehmti665
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Sonam Pathan
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Personfurqan222004
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Roomdivyansh0kumar0
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一Fs
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Roomdivyansh0kumar0
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Roomishabajaj13
 

Recently uploaded (20)

Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170Call Girls Near The Suryaa Hotel New Delhi 9873777170
Call Girls Near The Suryaa Hotel New Delhi 9873777170
 
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
定制(UAL学位证)英国伦敦艺术大学毕业证成绩单原版一比一
 
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
定制(CC毕业证书)美国美国社区大学毕业证成绩单原版一比一
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
Packaging the Monolith - PHP Tek 2024 (Breaking it down one bite at a time)
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
young call girls in Uttam Nagar🔝 9953056974 🔝 Delhi escort Service
 
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
Call Girls South Delhi Delhi reach out to us at ☎ 9711199012
 
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
Call Girls In The Ocean Pearl Retreat Hotel New Delhi 9873777170
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Complet Documnetation for Smart Assistant Application for Disabled Person
Complet Documnetation   for Smart Assistant Application for Disabled PersonComplet Documnetation   for Smart Assistant Application for Disabled Person
Complet Documnetation for Smart Assistant Application for Disabled Person
 
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Uttam Nagar Delhi 💯Call Us 🔝8264348440🔝
 
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130  Available With RoomVIP Kolkata Call Girl Kestopur 👉 8250192130  Available With Room
VIP Kolkata Call Girl Kestopur 👉 8250192130 Available With Room
 
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
定制(Management毕业证书)新加坡管理大学毕业证成绩单原版一比一
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
 
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With RoomVIP Kolkata Call Girl Salt Lake 👉 8250192130  Available With Room
VIP Kolkata Call Girl Salt Lake 👉 8250192130 Available With Room
 

13. Java text processing

  • 1. Text Processing Software University http://softuni.bg SoftUni Team Technical Trainers 1 Manipulating Text
  • 3. Table of Contents 1. What Is a String? 2. Manipulating Strings 3. Building and Modifying Strings  Using StringBuilder Class  Why Concatenation Is a Slow Operation? 3
  • 5.  Strings are sequences of characters (texts)  The string data type in Java  Declared by the String  Strings are enclosed in double quotes: What Is a String? 5 String text = "Hello, Java";
  • 6.  Strings are immutable (read-only) sequences of characters  Accessible by index (read-only)  Strings use Unicode (can use most alphabets, e.g. Arabic) Strings Are Immutable 6 String str = "Hello, Java"; char ch = str.charAt(2); // l String greeting = "你好"; // (lí-hó) Taiwanese
  • 7.  Initializing from a string literal:  Reading a string from the console:  Converting a string from and to a char array: Initializing a String 7 String str = "Hello, Java"; String name = sc.nextLine(); System.out.println("Hi, " + name); String str = new String(new char[] {'s', 't', 'r'}); char[] charArr = str.toCharArray(); // ['s', 't', 'r']
  • 9. Concatenating  Use the + or the += operators  Use the concat() method String greet = "Hello, "; String name = "John"; String result = greet.concat(name); System.out.println(result); // "Hello, John" String text = "Hello, "; text += "John"; // "Hello, John" String text = "Hello" + ", " + "world!"; // "Hello, world!" 8
  • 10. Joining Strings  String.join("", …) concatenates strings  Or an array/list of strings  Useful for repeating a string 10 String t = String.join("", "con", "ca", "ten", "ate"); // "concatenate" String s = "abc"; String[] arr = new String[3]; for (int i = 0; i < arr.length; i++) { arr[i] = s; } String repeated = String.join("", arr); // "abcabcabc"
  • 11.  Read an array from strings  Repeat each word n times, where n is the length of the word Problem: Repeat Strings 11 Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab hi abc add hihiabcabcabcaddaddadd work workworkworkwork ball ballballballball
  • 12. Solution: Repeat Strings (1) 12 String[] words = sc.nextLine().split(" "); List<String> result = new ArrayList<>(); for (String word : words) { result.add(repeat(word, word.length())); } System.out.println(String.join("", result)); Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
  • 13. static String repeat(String s, int repeatCount) { String[] repeatArr = new String[repeatCount]; for (int i = 0; i < repeatCount; i++) { repeatArr[i] = s; } return String.join("", repeatArr); } Solution: Repeat Strings (2) 13
  • 14. Substring  substring(int startIndex, int endIndex)  substring(int startIndex) 14 String text = "My name is John"; String extractWord = text.substring(11); System.out.println(extractWord); // John String card = "10C"; String power = card.substring(0, 2); System.out.println(power); // 10
  • 15. Searching (1)  indexOf() - returns the first match index or -1  lastIndexOf() - finds the last occurrence 15 String fruits = "banana, apple, kiwi, banana, apple"; System.out.println(fruits.lastIndexOf("banana")); // 21 System.out.println(fruits.lastIndexOf("orange")); // -1 String fruits = "banana, apple, kiwi, banana, apple"; System.out.println(fruits.indexOf("banana")); // 0 System.out.println(fruits.indexOf("orange")); // -1
  • 16. Searching (2)  contains() - checks whether one string contains another 16 String text = "I love fruits."; System.out.println(text.contains("fruits")); // true System.out.println(text.contains("banana")); // false
  • 17. Problem: Substring 17 Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab  You are given a remove word and a text  Remove all substrings that are equal to the remove word ice kicegiceiceb kgb abc tabctqw ttqw key keytextkey text word wordawordbwordc abc
  • 18. Solution: Substring 18 String key = sc.nextLine(); String text = sc.nextLine(); int index = text.indexOf(key); while (index != -1) { text = text.replace(key, ""); index = text.indexOf(key); } System.out.println(text); Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
  • 19. Splitting  Split a string by given pattern  Split by multiple separators 19 String text = "Hello, I am John."; String[] words = text.split("[, .]+"); // "Hello", "I", "am", "John" String text = "Hello, john@softuni.bg, you have been using john@softuni.bg in your registration"; String[] words = text.split(", "); // words[]: "Hello", "john@softuni.bg","you have been…"
  • 20. Replacing  replace(match, replacement) - replaces all occurrences  The result is a new string (strings are immutable) 20 String text = "Hello, john@softuni.bg, you have been using john@softuni.bg in your registration."; String replacedText = text .replace("john@softuni.bg", "john@softuni.com"); System.out.println(replacedText); // Hello, john@softuni.com, you have been using john@softuni.com in your registration.
  • 21. Problem: Text Filter 21 Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab  You are given a string of banned words and a text  Replace all banned words in the text with asterisks (*) Linux, Windows It is not Linux, it is GNU/Linux. Linux is merely the kernel, while GNU adds the functionality... It is not *****, it is GNU/*****. ***** is merely the kernel, while GNU adds the functionality...
  • 22. Solution: Text Filter (1) 22 String[] banWords = sc.nextLine.split(", "); String text = sc.nextLine(); for (String banWord : banWords) { if (text.contains(banWord)) { String replacement = repeatStr("*", banWord.length()); text = text.replace(banWord, replacement); } } System.out.println(text); contains(…) checks if string contains another string replace() a word with a sequence of asterisks of the same length Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
  • 23. Solution: Text Filter (2) 23 private static String repeatStr(String str, int length) { String replacement = ""; for (int i = 0; i < length; i++) { replacement += str; } return replacement; } Check your solution here: https://judge.softuni.bg/Contests/1669/Text-Processing-Lab
  • 25. Building and Modifying Strings Using the StringBuilder Class
  • 26.  StringBuilder keeps a buffer space, allocated in advance  Do not allocate memory for most operations  performance StringBuilder: How It Works? H e l l o , J A V AStringBuilder: length() = 10 capacity() = 16 Capacity used buffer (Length) unused buffer 24
  • 27. Using StringBuilder Class  Use the StringBuilder to build/modify strings 27 StringBuilder sb = new StringBuilder(); sb.append("Hello, "); sb.append("John! "); sb.append("I sent you an email."); System.out.println(sb.toString()); // Hello, John! I sent you an email.
  • 28. Concatenation vs. StringBuilder (1)  Concatenating strings is a slow operation because each iteration creates a new string 28 Tue Jul 10 13:57:20 EEST 2018 Tue Jul 10 13:58:07 EEST 2018 System.out.println(new Date()); String text = ""; for (int i = 0; i < 1000000; i++) text += "a"; System.out.println(new Date());
  • 29. Concatenation vs. StringBuilder (2)  Using StringBuilder 29 Tue Jul 10 14:51:31 EEST 2018 Tue Jul 10 14:51:31 EEST 2018 System.out.println(new Date()); StringBuilder text = new StringBuilder(); for (int i = 0; i < 1000000; i++) text.append("a"); System.out.println(new Date());
  • 30. StringBuilder Methods (1)  append() - appends the string representation of the argument  length() - holds the length of the string in the buffer  setLength(0) - removes all characters 30 StringBuilder sb = new StringBuilder(); sb.append("Hello Peter, how are you?"); sb.append("Hello Peter, how are you?"); System.out.println(sb.length()); // 25
  • 31. StringBuilder Methods (2)  charAt(int index) - returns char on index  insert(int index, String str) – inserts a string at the specified character position 31 StringBuilder sb = new StringBuilder(); sb.append("Hello Peter, how are you?"); System.out.println(sb.charAt(1)); // e sb.insert(11, " Ivanov"); System.out.println(sb); // Hello Peter Ivanov, how are you?
  • 32. StringBuilder Methods (3)  replace(int startIndex, int endIndex, String str) - replaces the chars in a substring  toString() - converts the value of this instance to a String 32 String text = sb.toString(); System.out.println(text); // Hello George, how are you? sb.append("Hello Peter, how are you?"); sb.replace(6, 11, "George");
  • 34.  …  …  … Summary 34  Strings are immutable sequences of Unicode characters  String processing methods  concat(), indexOf(), contains(), substring(), split(), replace(), …  StringBuilder efficiently builds/modifies strings
  • 38.  Software University – High-Quality Education and Employment Opportunities  softuni.bg  Software University Foundation  http://softuni.foundation/  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums  forum.softuni.bg Trainings @ Software University (SoftUni)
  • 39.  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution-NonCom mercial-ShareAlike 4.0 International" license License 39