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
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");
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
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!
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.
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.
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!
// 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);
}
}
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.
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