SlideShare una empresa de Scribd logo
1 de 38
Java Foundations
Strings and Text
Processing
Your Course
Instructors
Svetlin Nakov
George Georgiev
The Judge System
Sending your Solutions
for Automated Evaluation
Testing Your Code in the Judge System
 Test your code online in the SoftUni Judge system:
https://judge.softuni.org/Contests/3294
Text Processing
Manipulating Text
6
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?
7
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?
9
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
10
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
11
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!"
13
Joining Strings
 String.join("", …) concatenates strings
 Or an array/list of strings
 Useful for repeating a string
14
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
15
hi abc add hihiabcabcabcaddaddadd
work workworkworkwork
ball ballballballball
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));
Solution: Repeat Strings (1)
16
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)
17
Substring
 substring(int startIndex, int endIndex)
 substring(int startIndex)
18
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
19
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
20
String text = "I love fruits.";
System.out.println(text.contains("fruits"));
// true
System.out.println(text.contains("banana"));
// false
 You are given a remove word and a text
 Remove all substrings that are equal to the remove word
Problem: Substring
21
ice
kicegiceiceb
kgb
abc
tabctqw
ttqw
key
keytextkey
text
word
wordawordbwordc
abc
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);
Solution: Substring
22
Splitting
 Split a string by given pattern
 Split by multiple separators
23
String text = "Hello, I am John.";
String[] words = text.split("[, .]+");
// "Hello", "I", "am", "John"
String text = "Hello, john@softuni.org, you have been
using john@softuni.org in your registration";
String[] words = text.split(", ");
// words[]: "Hello","john@softuni.org","you have been…"
Replacing
 replace(match, replacement) - replaces all
occurrences
 The result is a new string (strings are immutable)
24
String text = "Hello, john@softuni.org, you have been
using john@softuni.org in your registration.";
String replacedText = text
.replace("john@softuni.org", "john@softuni.com");
System.out.println(replacedText);
// Hello, john@softuni.com, you have been using
john@softuni.com in your registration.
 You are given a string of banned words and a text
 Replace all banned words in the text with asterisks (*)
Problem: Text Filter
25
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...
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);
Solution: Text Filter (1)
26
contains(…) checks if string
contains another string
replace() a word with a sequence
of asterisks of the same length
private static String repeatStr(String str, int length) {
String replacement = "";
for (int i = 0; i < length; i++) {
replacement += str;
}
return replacement;
}
Solution: Text Filter (2)
27
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 a
StringBuilder:
length() = 10
capacity() = 16
Capacity
used buffer
(Length)
unused
buffer
30
Using StringBuilder Class
 Use the StringBuilder to build/modify strings
31
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
32
Tue Jul 10 13:57:20 EEST 2021
Tue Jul 10 13:58:07 EEST 2021
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
33
Tue Jul 10 14:51:31 EEST 2021
Tue Jul 10 14:51:31 EEST 2021
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
34
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
35
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
36
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
38
 Strings are immutable sequences of
Unicode characters
 String processing methods
 concat(), indexOf(), contains(),
substring(), split(), replace(), …
 StringBuilder efficiently builds/modifies
strings
 …
 …
 …
Next Steps
 Join the SoftUni "Learn To Code" Community
 Access the Free Coding Lessons
 Get Help from the Mentors
 Meet the Other Learners
https://softuni.org

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

09. Java Methods
09. Java Methods09. Java Methods
09. Java Methods
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
Java Foundations: Methods
Java Foundations: MethodsJava Foundations: Methods
Java Foundations: Methods
 
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...
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Java Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and CalculationsJava Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and Calculations
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
 
10. Recursion
10. Recursion10. Recursion
10. Recursion
 
16. Java stacks and queues
16. Java stacks and queues16. Java stacks and queues
16. Java stacks and queues
 
09. Methods
09. Methods09. Methods
09. Methods
 
06.Loops
06.Loops06.Loops
06.Loops
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
07. Arrays
07. Arrays07. Arrays
07. Arrays
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
 
20.1 Java working with abstraction
20.1 Java working with abstraction20.1 Java working with abstraction
20.1 Java working with abstraction
 

Similar a Java Foundations: Strings and 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-phpapp02
Abdul Samee
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
Adil Jafri
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
kamal kotecha
 

Similar a Java Foundations: Strings and Text Processing (20)

CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
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
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptxUsing-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
 
Lecture 2 java.pdf
Lecture 2 java.pdfLecture 2 java.pdf
Lecture 2 java.pdf
 
05 c++-strings
05 c++-strings05 c++-strings
05 c++-strings
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
 
lecture-5 string.pptx
lecture-5 string.pptxlecture-5 string.pptx
lecture-5 string.pptx
 
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
 
131 Lab slides (all in one)
131 Lab slides (all in one)131 Lab slides (all in one)
131 Lab slides (all in one)
 
11-ch04-3-strings.pdf
11-ch04-3-strings.pdf11-ch04-3-strings.pdf
11-ch04-3-strings.pdf
 
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)
 
Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2
 
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdfvision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
 
Write and write line methods
Write and write line methodsWrite and write line methods
Write and write line methods
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper classJava string , string buffer and wrapper class
Java string , string buffer and wrapper class
 
4java Basic Syntax
4java Basic Syntax4java Basic Syntax
4java Basic Syntax
 
String and string buffer
String and string bufferString and string buffer
String and string buffer
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
Python programming
Python  programmingPython  programming
Python programming
 

Más de Svetlin Nakov

Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
Svetlin Nakov
 

Más de Svetlin Nakov (20)

BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учителиBG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
 
Programming World in 2024
Programming World in 2024Programming World in 2024
Programming World in 2024
 
AI Tools for Business and Startups
AI Tools for Business and StartupsAI Tools for Business and Startups
AI Tools for Business and Startups
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
 
AI Tools for Entrepreneurs
AI Tools for EntrepreneursAI Tools for Entrepreneurs
AI Tools for Entrepreneurs
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal LifeAI Tools for Business and Personal Life
AI Tools for Business and Personal Life
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин НаковДипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООПДипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТСвободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
 
AI and the Professions of the Future
AI and the Professions of the FutureAI and the Professions of the Future
AI and the Professions of the Future
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023Programming Languages Trends for 2023
Programming Languages Trends for 2023
 
IT Professions and How to Become a Developer
IT Professions and How to Become a DeveloperIT Professions and How to Become a Developer
IT Professions and How to Become a Developer
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
 
IT Professions and Their Future
IT Professions and Their FutureIT Professions and Their Future
IT Professions and Their Future
 
How to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a JobHow to Become a QA Engineer and Start a Job
How to Become a QA Engineer and Start a Job
 
Призвание и цели: моята рецепта
Призвание и цели: моята рецептаПризвание и цели: моята рецепта
Призвание и цели: моята рецепта
 
What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?What Mongolian IT Industry Can Learn from Bulgaria?
What Mongolian IT Industry Can Learn from Bulgaria?
 
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
How to Become a Software Developer - Nakov in Mongolia (Oct 2022)
 
Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)Blockchain and DeFi Overview (Nakov, Sept 2021)
Blockchain and DeFi Overview (Nakov, Sept 2021)
 

Último

Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 

Último (20)

Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
WSO2CON 2024 - Building the API First Enterprise – Running an API Program, fr...
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni%in Benoni+277-882-255-28 abortion pills for sale in Benoni
%in Benoni+277-882-255-28 abortion pills for sale in Benoni
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 

Java Foundations: Strings and Text Processing

  • 3. The Judge System Sending your Solutions for Automated Evaluation
  • 4. Testing Your Code in the Judge System  Test your code online in the SoftUni Judge system: https://judge.softuni.org/Contests/3294
  • 6. 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? 7
  • 8.  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? 9 String text = "Hello, Java";
  • 9.  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 10 String str = "Hello, Java"; char ch = str.charAt(2); // l String greeting = "你好"; // (lí-hó) Taiwanese
  • 10.  Initializing from a string literal:  Reading a string from the console:  Converting a string from and to a char array: Initializing a String 11 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']
  • 12. 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!" 13
  • 13. Joining Strings  String.join("", …) concatenates strings  Or an array/list of strings  Useful for repeating a string 14 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"
  • 14.  Read an array from strings  Repeat each word n times, where n is the length of the word Problem: Repeat Strings 15 hi abc add hihiabcabcabcaddaddadd work workworkworkwork ball ballballballball
  • 15. 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)); Solution: Repeat Strings (1) 16
  • 16. 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) 17
  • 17. Substring  substring(int startIndex, int endIndex)  substring(int startIndex) 18 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
  • 18. Searching (1)  indexOf() - returns the first match index or -1  lastIndexOf() - finds the last occurrence 19 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
  • 19. Searching (2)  contains() - checks whether one string contains another 20 String text = "I love fruits."; System.out.println(text.contains("fruits")); // true System.out.println(text.contains("banana")); // false
  • 20.  You are given a remove word and a text  Remove all substrings that are equal to the remove word Problem: Substring 21 ice kicegiceiceb kgb abc tabctqw ttqw key keytextkey text word wordawordbwordc abc
  • 21. 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); Solution: Substring 22
  • 22. Splitting  Split a string by given pattern  Split by multiple separators 23 String text = "Hello, I am John."; String[] words = text.split("[, .]+"); // "Hello", "I", "am", "John" String text = "Hello, john@softuni.org, you have been using john@softuni.org in your registration"; String[] words = text.split(", "); // words[]: "Hello","john@softuni.org","you have been…"
  • 23. Replacing  replace(match, replacement) - replaces all occurrences  The result is a new string (strings are immutable) 24 String text = "Hello, john@softuni.org, you have been using john@softuni.org in your registration."; String replacedText = text .replace("john@softuni.org", "john@softuni.com"); System.out.println(replacedText); // Hello, john@softuni.com, you have been using john@softuni.com in your registration.
  • 24.  You are given a string of banned words and a text  Replace all banned words in the text with asterisks (*) Problem: Text Filter 25 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...
  • 25. 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); Solution: Text Filter (1) 26 contains(…) checks if string contains another string replace() a word with a sequence of asterisks of the same length
  • 26. private static String repeatStr(String str, int length) { String replacement = ""; for (int i = 0; i < length; i++) { replacement += str; } return replacement; } Solution: Text Filter (2) 27
  • 28. Building and Modifying Strings Using the StringBuilder Class
  • 29.  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 a StringBuilder: length() = 10 capacity() = 16 Capacity used buffer (Length) unused buffer 30
  • 30. Using StringBuilder Class  Use the StringBuilder to build/modify strings 31 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.
  • 31. Concatenation vs. StringBuilder (1)  Concatenating strings is a slow operation because each iteration creates a new string 32 Tue Jul 10 13:57:20 EEST 2021 Tue Jul 10 13:58:07 EEST 2021 System.out.println(new Date()); String text = ""; for (int i = 0; i < 1000000; i++) text += "a"; System.out.println(new Date());
  • 32. Concatenation vs. StringBuilder (2)  Using StringBuilder 33 Tue Jul 10 14:51:31 EEST 2021 Tue Jul 10 14:51:31 EEST 2021 System.out.println(new Date()); StringBuilder text = new StringBuilder(); for (int i = 0; i < 1000000; i++) text.append("a"); System.out.println(new Date());
  • 33. 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 34 StringBuilder sb = new StringBuilder(); sb.append("Hello Peter, how are you?"); sb.append("Hello Peter, how are you?"); System.out.println(sb.length()); // 25
  • 34. StringBuilder Methods (2)  charAt(int index) - returns char on index  insert(int index, String str) – inserts a string at the specified character position 35 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?
  • 35. 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 36 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");
  • 37.  …  …  … Summary 38  Strings are immutable sequences of Unicode characters  String processing methods  concat(), indexOf(), contains(), substring(), split(), replace(), …  StringBuilder efficiently builds/modifies strings
  • 38.  …  …  … Next Steps  Join the SoftUni "Learn To Code" Community  Access the Free Coding Lessons  Get Help from the Mentors  Meet the Other Learners https://softuni.org

Notas del editor

  1. Hello, I am Svetlin Nakov from SoftUni (the Software University). Together with my colleague George Georgiev, we shall teach this free Java Foundations course, which covers important concepts from Java programming, such as arrays, lists, methods, strings, classes, objects and exceptions, and prepares you for the "Java Foundations" official exam from Oracle. In this lesson your instructor George will demonstrate how to use strings to process text in Java. Working with text data in Java involves the use of the String data type, which contains an immutable sequence of text characters, and the StringBuilder type, which allows efficiently creating large texts. The String class in Java allows searching in a string, inserting and deleting substrings from a string, splitting a string by certain delimiter, joining several strings into a larger string and many other text processing operations. Let's learn them through live coding examples, and later solve some hands-on exercises to gain practical experience. Are you ready? Let's start!
  2. Before the start, I would like to introduce your course instructors: Svetlin Nakov and George Georgiev, who are experienced Java developers, senior software engineers and inspirational tech trainers. They have spent thousands of hours teaching programming and software technologies and are top trainers from SoftUni. I am sure you will like how they teach programming.
  3. Most of this course will be taught by George Georgiev, who is a senior software engineer with many years of experience with Java, JavaScript and C++. George enjoys teaching programming very much and is one of the top trainers at the Software University, having delivered over 300 technical training sessions on the topics of data structures and algorithms, Java essentials, Java fundamentals, C++ programming, C# development and many others. I have no doubt you will benefit greatly from his lessons, as he always does his best to explain the most challenging concepts in a simple and fun way.
  4. Before we dive into the course, I want to show you the SoftUni judge system, where you can get instant feedback for your exercise solutions. SoftUni Judge is an automated system for code evaluation. You just send your code for a certain coding problem and the system will tell you whether your solution is correct or not and what exactly is missing or wrong. I am sure you will love the judge system, once you start using it!
  5. // Solution to problem "01. Student Information". import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String name = sc.nextLine(); int age = Integer.parseInt(sc.nextLine()); double grade = Double.parseDouble(sc.nextLine()); System.out.printf("Name: %s, Age: %d, Grade: %.2f", name, age, grade); } }
  6. In this section, we shall learn how to process text in Java. Working with text data in Java involves the use of the String data type, which contains a sequence of text characters, and the StringBuilder type, which allows efficient generation of large texts. The standard Java API allows searching in a string, inserting and deleting substrings from a string, splitting a string by certain delimiter, joining several strings into a larger string and many other operations. Let's learn how to use strings in Java and how to process text data. Remember that learning a skill is only possible through practice, and you should write solutions to the hands-on exercises, coming with this course topic. Exercises are quite more important than the theory. If you skip them, you can't develop your skills. Now, it's time to invite George to teach this topic.
  7. Did you like this lesson? Do you want more? Join the learners' community at softuni.org. Subscribe to my YouTube channel to get more free video tutorials on coding and software development. Get free access to the practical exercises and the automated judge system for this coding lesson. Get free help from mentors and meet other learners. Join now! It's free. SOFTUNI.ORG