SlideShare a Scribd company logo
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

PPTX
07. Java Array, Set and Maps
Intro C# Book
 
PPTX
13 Strings and Text Processing
Intro C# Book
 
PPTX
09. Java Methods
Intro C# Book
 
PPTX
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
PPTX
07. Arrays
Intro C# Book
 
PPTX
19. Java data structures algorithms and complexity
Intro C# Book
 
07. Java Array, Set and Maps
Intro C# Book
 
13 Strings and Text Processing
Intro C# Book
 
09. Java Methods
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
16. Arrays Lists Stacks Queues
Intro C# Book
 
07. Arrays
Intro C# Book
 
19. Java data structures algorithms and complexity
Intro C# Book
 

What's hot (20)

PPTX
05. Java Loops Methods and Classes
Intro C# Book
 
PPTX
15. Streams Files and Directories
Intro C# Book
 
PPTX
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
16. Java stacks and queues
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
PPTX
10. Recursion
Intro C# Book
 
PPTX
06.Loops
Intro C# Book
 
PPTX
09. Methods
Intro C# Book
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PPTX
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
PPTX
02. Primitive Data Types and Variables
Intro C# Book
 
PPTX
Java Foundations: Arrays
Svetlin Nakov
 
PPT
Chapter 2 Java Methods
Khirulnizam Abd Rahman
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PPT
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
PDF
Java Basics - Part1
Vani Kandhasamy
 
PPT
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
PPTX
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
PPTX
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
05. Java Loops Methods and Classes
Intro C# Book
 
15. Streams Files and Directories
Intro C# Book
 
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
16. Java stacks and queues
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 
10. Recursion
Intro C# Book
 
06.Loops
Intro C# Book
 
09. Methods
Intro C# Book
 
20.1 Java working with abstraction
Intro C# Book
 
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
02. Primitive Data Types and Variables
Intro C# Book
 
Java Foundations: Arrays
Svetlin Nakov
 
Chapter 2 Java Methods
Khirulnizam Abd Rahman
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
Chapter 4 - Classes in Java
Khirulnizam Abd Rahman
 
Java Basics - Part1
Vani Kandhasamy
 
Chapter 3 Arrays in Java
Khirulnizam Abd Rahman
 
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Java Foundations: Data Types and Type Conversion
Svetlin Nakov
 
Ad

Similar to 13. Java text processing (20)

PPSX
String and string manipulation x
Shahjahan Samoon
 
PPTX
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
PPTX
Java string handling
GaneshKumarKanthiah
 
PPT
Java Strings methods and operations.ppt
JyothiAmpally
 
PPT
String and string manipulation
Shahjahan Samoon
 
PPTX
Strings in Java
Abhilash Nair
 
PDF
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
PPTX
10619416141061941614.106194161fff4..pptx
Shwetamaurya36
 
PPTX
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
PPTX
Java String Handling
Infoviaan Technologies
 
PPTX
L13 string handling(string class)
teach4uin
 
PPTX
String.pptx
RanjithKumar742256
 
PPTX
Java Strings
RaBiya Chaudhry
 
PPT
Comp102 lec 9
Fraz Bakhsh
 
PPS
String and string buffer
kamal kotecha
 
PPT
Strings v.1.1
BG Java EE Course
 
PPT
String classes and its methods.20
myrajendra
 
PPSX
Java String class
DrRajeshreeKhande
 
PPT
Strings.ppt
SanthiyaAK
 
PPTX
STRING FUNCTIONS IN JAVA BY N SARATH KUMAR
Sarathkumar Narsupalli
 
String and string manipulation x
Shahjahan Samoon
 
21CS642 Module 3 Strings PPT.pptx VI SEM CSE
VENKATESHBHAT25
 
Java string handling
GaneshKumarKanthiah
 
Java Strings methods and operations.ppt
JyothiAmpally
 
String and string manipulation
Shahjahan Samoon
 
Strings in Java
Abhilash Nair
 
Module-1 Strings Handling.ppt.pdf
learnEnglish51
 
10619416141061941614.106194161fff4..pptx
Shwetamaurya36
 
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Java String Handling
Infoviaan Technologies
 
L13 string handling(string class)
teach4uin
 
String.pptx
RanjithKumar742256
 
Java Strings
RaBiya Chaudhry
 
Comp102 lec 9
Fraz Bakhsh
 
String and string buffer
kamal kotecha
 
Strings v.1.1
BG Java EE Course
 
String classes and its methods.20
myrajendra
 
Java String class
DrRajeshreeKhande
 
Strings.ppt
SanthiyaAK
 
STRING FUNCTIONS IN JAVA BY N SARATH KUMAR
Sarathkumar Narsupalli
 
Ad

More from Intro C# Book (16)

PPTX
17. Java data structures trees representation and traversal
Intro C# Book
 
PPTX
Java Problem solving
Intro C# Book
 
PPTX
21. Java High Quality Programming Code
Intro C# Book
 
PPTX
20.5 Java polymorphism
Intro C# Book
 
PPTX
20.4 Java interfaces and abstraction
Intro C# Book
 
PPTX
20.3 Java encapsulation
Intro C# Book
 
PPTX
20.2 Java inheritance
Intro C# Book
 
PPTX
18. Java associative arrays
Intro C# Book
 
PPTX
14. Java defining classes
Intro C# Book
 
PPTX
12. Java Exceptions and error handling
Intro C# Book
 
PPTX
11. Java Objects and classes
Intro C# Book
 
PPTX
01. Introduction to programming with java
Intro C# Book
 
PPTX
23. Methodology of Problem Solving
Intro C# Book
 
PPTX
21. High-Quality Programming Code
Intro C# Book
 
PPTX
17. Trees and Tree Like Structures
Intro C# Book
 
PPTX
14 Defining Classes
Intro C# Book
 
17. Java data structures trees representation and traversal
Intro C# Book
 
Java Problem solving
Intro C# Book
 
21. Java High Quality Programming Code
Intro C# Book
 
20.5 Java polymorphism
Intro C# Book
 
20.4 Java interfaces and abstraction
Intro C# Book
 
20.3 Java encapsulation
Intro C# Book
 
20.2 Java inheritance
Intro C# Book
 
18. Java associative arrays
Intro C# Book
 
14. Java defining classes
Intro C# Book
 
12. Java Exceptions and error handling
Intro C# Book
 
11. Java Objects and classes
Intro C# Book
 
01. Introduction to programming with java
Intro C# Book
 
23. Methodology of Problem Solving
Intro C# Book
 
21. High-Quality Programming Code
Intro C# Book
 
17. Trees and Tree Like Structures
Intro C# Book
 
14 Defining Classes
Intro C# Book
 

Recently uploaded (20)

PDF
Elements Of Poetry PowerPoint With Sources
PrincessKate16
 
PDF
DNSSEC Made Easy, presented at PHNOG 2025
APNIC
 
PPTX
ENCOR_Chapter_10 - OSPFv3 Attribution.pptx
nshg93
 
PDF
Slides PDF The Workd Game (s) Eco Economic Epochs.pdf
Steven McGee
 
PPTX
durere- in cancer tu ttresjjnklj gfrrjnrs mhugyfrd
Serban Elena
 
PPTX
Unlocking Hope : How Crypto Recovery Services Can Reclaim Your Lost Funds
lionsgate network
 
PDF
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
PDF
Data Protection & Resilience in Focus.pdf
AmyPoblete3
 
PPTX
Google SGE SEO: 5 Critical Changes That Could Wreck Your Rankings in 2025
Reversed Out Creative
 
PDF
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
LABUAN 4D
 
PPTX
SEO Trends in 2025 | B3AITS - Bow & 3 Arrows IT Solutions
B3AITS - Bow & 3 Arrows IT Solutions
 
PPTX
AI ad its imp i military life read it ag
ShwetaBharti31
 
PPTX
Parallel & Concurrent ...
yashpavasiya892
 
PPTX
Generics jehfkhkshfhskjghkshhhhlshluhueheuhuhhlhkhk.pptx
yashpavasiya892
 
PDF
“Google Algorithm Updates in 2025 Guide”
soohhhnah
 
PPTX
Crypto Recovery California Services.pptx
lionsgate network
 
PPTX
CSharp_Syntax_Basics.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxx
nhdqw45qfd
 
PPTX
PPT_M4.3_WORKING WITH SLIDES APPLIED.pptx
MCEAMONVILLAVER
 
PDF
Generative AI Foundations: AI Skills for the Future of Work
hemal sharma
 
PDF
Centralized Business Email Management_ How Admin Controls Boost Efficiency & ...
XgenPlus Technologies
 
Elements Of Poetry PowerPoint With Sources
PrincessKate16
 
DNSSEC Made Easy, presented at PHNOG 2025
APNIC
 
ENCOR_Chapter_10 - OSPFv3 Attribution.pptx
nshg93
 
Slides PDF The Workd Game (s) Eco Economic Epochs.pdf
Steven McGee
 
durere- in cancer tu ttresjjnklj gfrrjnrs mhugyfrd
Serban Elena
 
Unlocking Hope : How Crypto Recovery Services Can Reclaim Your Lost Funds
lionsgate network
 
KIPER4D situs Exclusive Game dari server Star Gaming Asia
hokimamad0
 
Data Protection & Resilience in Focus.pdf
AmyPoblete3
 
Google SGE SEO: 5 Critical Changes That Could Wreck Your Rankings in 2025
Reversed Out Creative
 
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
LABUAN 4D
 
SEO Trends in 2025 | B3AITS - Bow & 3 Arrows IT Solutions
B3AITS - Bow & 3 Arrows IT Solutions
 
AI ad its imp i military life read it ag
ShwetaBharti31
 
Parallel & Concurrent ...
yashpavasiya892
 
Generics jehfkhkshfhskjghkshhhhlshluhueheuhuhhlhkhk.pptx
yashpavasiya892
 
“Google Algorithm Updates in 2025 Guide”
soohhhnah
 
Crypto Recovery California Services.pptx
lionsgate network
 
CSharp_Syntax_Basics.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxx
nhdqw45qfd
 
PPT_M4.3_WORKING WITH SLIDES APPLIED.pptx
MCEAMONVILLAVER
 
Generative AI Foundations: AI Skills for the Future of Work
hemal sharma
 
Centralized Business Email Management_ How Admin Controls Boost Efficiency & ...
XgenPlus Technologies
 

13. Java text processing

  • 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, [email protected], you have been using [email protected] in your registration"; String[] words = text.split(", "); // words[]: "Hello", "[email protected]","you have been…"
  • 20. Replacing  replace(match, replacement) - replaces all occurrences  The result is a new string (strings are immutable) 20 String text = "Hello, [email protected], you have been using [email protected] in your registration."; String replacedText = text .replace("[email protected]", "[email protected]"); System.out.println(replacedText); // Hello, [email protected], you have been using [email protected] 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