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

More Related Content

What's hot (20)

09. Java Methods
09. Java Methods
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
Java Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
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
 
13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
Intro C# Book
 
07. Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
Java Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and Calculations
Svetlin Nakov
 
Java Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
10. Recursion
10. Recursion
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
09. Methods
09. Methods
Intro C# Book
 
06.Loops
06.Loops
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
11. Java Objects and classes
11. Java Objects and classes
Intro C# Book
 
07. Arrays
07. Arrays
Intro C# Book
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
Intro C# Book
 
Java Foundations: Methods
Java Foundations: Methods
Svetlin Nakov
 
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
 
13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
19. Data Structures and Algorithm Complexity
19. Data Structures and Algorithm Complexity
Intro C# Book
 
07. Java Array, Set and Maps
07. Java Array, Set and Maps
Intro C# Book
 
Java Tutorial: Part 4 - Data and Calculations
Java Tutorial: Part 4 - Data and Calculations
Svetlin Nakov
 
Java Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 
15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
16. Arrays Lists Stacks Queues
16. Arrays Lists Stacks Queues
Intro C# Book
 
16. Java stacks and queues
16. Java stacks and queues
Intro C# Book
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
Intro C# Book
 
11. Java Objects and classes
11. Java Objects and classes
Intro C# Book
 
02. Primitive Data Types and Variables
02. Primitive Data Types and Variables
Intro C# Book
 
20.1 Java working with abstraction
20.1 Java working with abstraction
Intro C# Book
 

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

CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
UadAccount
 
Lecture 2 java.pdf
Lecture 2 java.pdf
SantoshSurwade2
 
String class and function for b.tech iii year students
String class and function for b.tech iii year students
Somesh Kumar
 
C string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CG
drsomeshdewangan
 
05 c++-strings
05 c++-strings
Kelly Swanson
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
Ananthi68
 
String in java, string constructors and operations
String in java, string constructors and operations
manjeshbngowda
 
lecture-5 string.pptx
lecture-5 string.pptx
DilanAlmsa
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
131 Lab slides (all in one)
131 Lab slides (all in one)
Tak Lee
 
11-ch04-3-strings.pdf
11-ch04-3-strings.pdf
AndreaBatholomeo
 
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
 
Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2
NayanTapare1
 
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
bhagyashri686896
 
Write and write line methods
Write and write line methods
Dr.M.Karthika parthasarathy
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
Prabu U
 
Using-Python-Libraries.9485146.powerpoint.pptx
Using-Python-Libraries.9485146.powerpoint.pptx
UadAccount
 
String class and function for b.tech iii year students
String class and function for b.tech iii year students
Somesh Kumar
 
C string _updated_Somesh_SSTC_ Bhilai_CG
C string _updated_Somesh_SSTC_ Bhilai_CG
drsomeshdewangan
 
3.7_StringBuilder.pdf
3.7_StringBuilder.pdf
Ananthi68
 
String in java, string constructors and operations
String in java, string constructors and operations
manjeshbngowda
 
lecture-5 string.pptx
lecture-5 string.pptx
DilanAlmsa
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Charcater and Strings.ppt Charcater and Strings.ppt
Charcater and Strings.ppt Charcater and Strings.ppt
mulualem37
 
131 Lab slides (all in one)
131 Lab slides (all in one)
Tak Lee
 
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
 
Vision academy classes_bcs_bca_bba_java part_2
Vision academy classes_bcs_bca_bba_java part_2
NayanTapare1
 
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
vision_academy_classes_Bcs_bca_bba_java part_2 (1).pdf
bhagyashri686896
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
Ad

More from Svetlin Nakov (20)

AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024
Svetlin Nakov
 
Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
Programming World in 2024
Programming World in 2024
Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for Entrepreneurs
Svetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal Life
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the Future
Svetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023
Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a Developer
Svetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
AI and the Future of Devs: Nakov @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI за ежедневието - Наков @ Techniverse (Nov 2024)
AI за ежедневието - Наков @ Techniverse (Nov 2024)
Svetlin Nakov
 
AI инструменти за бизнеса - Наков - Nov 2024
AI инструменти за бизнеса - Наков - Nov 2024
Svetlin Nakov
 
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
AI Adoption in Business - Nakov at Forbes HR Forum - Sept 2024
Svetlin Nakov
 
Software Engineers in the AI Era - Sept 2024
Software Engineers in the AI Era - Sept 2024
Svetlin Nakov
 
Най-търсените направления в ИТ сферата за 2024
Най-търсените направления в ИТ сферата за 2024
Svetlin Nakov
 
BG-IT-Edu: отворено учебно съдържание за ИТ учители
BG-IT-Edu: отворено учебно съдържание за ИТ учители
Svetlin Nakov
 
Programming World in 2024
Programming World in 2024
Svetlin Nakov
 
AI Tools for Business and Startups
AI Tools for Business and Startups
Svetlin Nakov
 
AI Tools for Scientists - Nakov (Oct 2023)
AI Tools for Scientists - Nakov (Oct 2023)
Svetlin Nakov
 
AI Tools for Entrepreneurs
AI Tools for Entrepreneurs
Svetlin Nakov
 
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Bulgarian Tech Industry - Nakov at Dev.BG All in One Conference 2023
Svetlin Nakov
 
AI Tools for Business and Personal Life
AI Tools for Business and Personal Life
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Дипломна работа: учебно съдържание по ООП - Светлин Наков
Svetlin Nakov
 
Дипломна работа: учебно съдържание по ООП
Дипломна работа: учебно съдържание по ООП
Svetlin Nakov
 
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Свободно ИТ учебно съдържание за учители по програмиране и ИТ
Svetlin Nakov
 
AI and the Professions of the Future
AI and the Professions of the Future
Svetlin Nakov
 
Programming Languages Trends for 2023
Programming Languages Trends for 2023
Svetlin Nakov
 
IT Professions and How to Become a Developer
IT Professions and How to Become a Developer
Svetlin Nakov
 
GitHub Actions (Nakov at RuseConf, Sept 2022)
GitHub Actions (Nakov at RuseConf, Sept 2022)
Svetlin Nakov
 
Ad

Recently uploaded (20)

dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 
dp-700 exam questions sample docume .pdf
dp-700 exam questions sample docume .pdf
pravkumarbiz
 
How the US Navy Approaches DevSecOps with Raise 2.0
How the US Navy Approaches DevSecOps with Raise 2.0
Anchore
 
Advanced Token Development - Decentralized Innovation
Advanced Token Development - Decentralized Innovation
arohisinghas720
 
Step by step guide to install Flutter and Dart
Step by step guide to install Flutter and Dart
S Pranav (Deepu)
 
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
DevOps for AI: running LLMs in production with Kubernetes and KubeFlow
Aarno Aukia
 
SAP PM Module Level-IV Training Complete.ppt
SAP PM Module Level-IV Training Complete.ppt
MuhammadShaheryar36
 
Open Source Software Development Methods
Open Source Software Development Methods
VICTOR MAESTRE RAMIREZ
 
Porting Qt 5 QML Modules to Qt 6 Webinar
Porting Qt 5 QML Modules to Qt 6 Webinar
ICS
 
What is data visualization and how data visualization tool can help.pdf
What is data visualization and how data visualization tool can help.pdf
Varsha Nayak
 
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Looking for a BIRT Report Alternative Here’s Why Helical Insight Stands Out.pdf
Varsha Nayak
 
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
Microsoft Business-230T01A-ENU-PowerPoint_01.pptx
soulamaabdoulaye128
 
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
Milwaukee Marketo User Group June 2025 - Optimize and Enhance Efficiency - Sm...
BradBedford3
 
Who will create the languages of the future?
Who will create the languages of the future?
Jordi Cabot
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Artificial Intelligence Applications Across Industries
Artificial Intelligence Applications Across Industries
SandeepKS52
 
Agile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Wondershare PDFelement Pro 11.4.20.3548 Crack Free Download
Puppy jhon
 
wAIred_RabobankIgniteSession_12062025.pptx
wAIred_RabobankIgniteSession_12062025.pptx
SimonedeGijt
 
Reimagining Software Development and DevOps with Agentic AI
Reimagining Software Development and DevOps with Agentic AI
Maxim Salnikov
 
How Insurance Policy Management Software Streamlines Operations
How Insurance Policy Management Software Streamlines Operations
Insurance Tech Services
 

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

Editor's Notes

  • #2: 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!
  • #3: 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.
  • #4: 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.
  • #5: 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!
  • #6: // 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); } }
  • #7: 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.
  • #40: 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