SlideShare a Scribd company logo
Strings and Text Processing
Processing and Manipulating Text
Using the .NET String Class
SoftUni Team
Technical Trainers
Software University
http://softuni.bg
Table of Contents
1. What is a String?
2. Manipulating Strings
 Comparing, Concatenating, Searching
 Extracting Substrings, Splitting
3. Building and Modifying Strings
 Why Is the + Operator Slow?
 Using the StringBuilder Class
2
3
Questions
sli.do
#fund-softuni
Strings
What is a String?
5
 Strings are sequences of characters (texts)
 The string data type in C#
 Declared by the string keyword
 Maps to System.String .NET data type
 Strings are enclosed in quotes:
 Concatenated using the "+" operator:
Strings
string s = "Hello, C#";
string s = "Hello" + " " + "C#";
6
 Strings are immutable (read-only) sequences of characters
 Accessible by index (read-only)
 Strings use Unicode (can use most alphabets, e.g. Arabic)
In C# Strings are Immutable, use Unicode
string str =
"Hello, C#";
let ch = str[2]; // OK
str[2] = 'a'; // Error!
string greeting = "ْ‫م‬ُ‫ك‬ْ‫ي‬‫ا‬‫ل‬‫ا‬‫ع‬ ُ‫م‬‫ا‬‫َل‬َّ‫;"الس‬ // As-salamu alaykum
0 1 2 3 4 5 6 7 8
H e l l o , C #
index =
str[index] =
7
 Initializing from a string literal:
 Reading a string from the console:
 Converting a string from and to a char array:
Initializing a String
string str = "Hello, C#";
string name = Console.ReadLine();
Console.WriteLine("Hi, " + name);
string str = new String(new char[] {'s', 't', 'r'});
char[] charArr = str.ToCharArray(); // ['s', 't', 'r']
0 1 2 3 4 5 6 7 8
H e l l o , C #
Manipulating Strings
Comparing, Concatenating, Searching,
Extracting Substrings, Splitting
9
 Ordinal (exact binary) string comparison
 Case-insensitive string comparison
 Case-sensitive string comparison
Comparing Strings
int result = string.Compare(str1, str2, true);
// result == 0 if str1 equals str2
// result < 0 if str1 is before str2
// result > 0 if str1 is after str2
int result = string.Compare(str1, str2, false);
int eq = (str1 == str2); // uses String.Equals(…)
Concatenating (Combining) Strings
 Use the Concat() method
 Use the + or the += operators
 Any object can be appended to a string
string str = string.Concat(str1, str2);
string str = str1 + str2 + str3;
string str += str1;
string name = "Peter"; int age = 22;
string s = name + " " + age; //  "Peter 22"
10
11
 Finding a substring within a given string
 str.IndexOf(string term) – returns the first index or -1
 str.LastIndexOf(string term) – finds the last occurence
Searching in Strings
string email = "vasko@gmail.org";
int firstIndex = email.IndexOf("@"); // 5
int secondIndex = email.IndexOf("a", 2); // 8
int notFound = email.IndexOf("/"); // -1
string verse = "To be or not to be…";
int lastIndex = verse.LastIndexOf("be"); // 16
12
Problem: Count Substring Occurrences
 You are given a text and a pattern
 Find how many times that pattern occurs in the text
 Overlapping is allowed
Welcome to SoftUni
Java
0
ababa caba
aba
3
aaaaaa
aa
5
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/320#1
13
Solution: Count Substring Occurrences
string input = Console.ReadLine().ToLower();
string pattern = Console.ReadLine().ToLower();
int counter = 0;
int index = input.IndexOf(pattern);
while (index != -1)
{
counter++;
index = input.IndexOf(pattern, index + 1)
}
Console.WriteLine(counter);
Extracting Substrings
 str.Substring(int startIndex, int length)
 str.Substring(int startIndex)
string filename = @"C:PicsRila2017.jpg";
string name = filename.Substring(8, 8);
// name == "Rila2017"
string filename = @"C:PicsRila2017.jpg";
string nameAndExtension = filename.Substring(8);
// nameAndExtension == "Rila2017.jpg"
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
C :  P i c s  R i l a 2 0 1 7 . j p g
14
Splitting Strings
 Split a string by given separator(s) :
 Example:
string[] Split(params char[] separator)
string listOfBeers = "Amstel, Zagorka, Tuborg, Becks.";
string[] beers = listOfBeers.Split(' ', ',', '.');
Console.WriteLine("Available beers are:");
foreach (string beer in beers)
Console.WriteLine(beer);
15
Other String Operations
Replacing and Deleting Substrings,
Changing Character Casing, Trimming
Replacing and Deleting Substrings
 str.Replace(match, replacement) – replaces all occurrences
 The result is a new string (strings are immutable)
 str.Remove(int index, int length) – deletes part of a string
 Produces a new string as result
string cocktail = "Vodka + Martini + Cherry";
string replaced = cocktail.Replace("+", "and");
// Vodka and Martini and Cherry
string price = "$ 1234567";
string lowPrice = price.Remove(2, 3);
// $ 4567
17
18
Problem: Text Filter (Banned Words)
 You are given a text and a string of banned words
 Replace all banned words in the text with asterisks
 Replace with asterisks (*), whose count is equal to the word's length
Linux, Windows
It is not Linux, it is GNU/Linux. Linux is merely
the kernel, while GNU adds the functionality...
Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/320#2
It is not *****, it is GNU/*****. ***** is merely
the kernel, while GNU adds the functionality...
19
Solution: Text Filter
string[] banWords = Console.ReadLine()
.Split(…); // TODO: add separators
string text = Console.ReadLine();
foreach (var banWord in banWords)
{
if (text.Contains(banWord))
{
text = text.Replace(banWord,
new string('*', banWord.Length));
}
}
Console.WriteLine(text);
Contains(…) checks
if string contains
another string
Replace a word with a sequence
of asterisks of the same length
Changing Character Casing
 Using the method ToLower()
 Using the method ToUpper()
string alpha = "aBcDeFg";
string lowerAlpha = alpha.ToLower(); // abcdefg
Console.WriteLine(lowerAlpha);
string alpha = "aBcDeFg";
string upperAlpha = alpha.ToUpper(); // ABCDEFG
Console.WriteLine(upperAlpha);
20
21
 str.Trim() – trims whitespaces at start and end of string
 str.Trim(params char[] chars)
 str.TrimStart() and str.TrimEnd()
Trimming White Space
string s = " example of white space ";
string clean = s.Trim();
Console.WriteLine(clean); // example of white space
string s = " tnHello!!! n";
string clean = s.Trim(' ', ',' ,'!', 'n','t');
Console.WriteLine(clean); // Hello
string s = " C# ";
string clean = s.TrimStart(); // clean = "C# "
Live Exercises in Class (Lab)
String Operations
Building and Modifying Strings
Using the StringBuilder Class
StringBuilder: How It Works?
 StringBuilder keeps a buffer space, allocated in advance
 Do not allocate memory for most operations  performance
H e l l o , C # !StringBuilder:
Length = 9
Capacity = 15
Capacity
used buffer
(Length)
unused
buffer
24
25
 Use the System.Text.StringBuilder to build / modify strings:
Changing the Contents of a String
public static string ReverseString(string str)
{
StringBuilder sb = new StringBuilder();
for (int i = str.Length - 1; i >= 0; i--)
{
sb.Append(str[i]);
}
return sb.ToString();
}
The StringBuilder Class
 StringBuilder(int capacity) constructor allocates in
advance buffer of size capacity
 Capacity holds the currently allocated space (in characters)
 Length holds the length of the string in the buffer
 this[int index] (indexer) access the char at given position
26
H e l l o , C # !
Capacity
used buffer (Length) unused buffer
27
StringBuilder Operations – Examples
var builder = new StringBuilder(100);
builder.Append("Hello Maria, how are you?");
Console.WriteLine(builder); // Hello Maria, how are you?
builder[6] = 'D';
Console.WriteLine(builder); // Hello Daria, how are you?
builder.Remove(5, 6);
Console.WriteLine(builder); // Hello, how are you?
builder.Insert(5, " Peter");
Console.WriteLine(builder); // Hello Peter, how are you?
builder.Replace("Peter", "George");
Console.WriteLine(builder); // Hello George, how are you?
28
Problem: String Concatenation
 Given the code below try to optimize it to go under a second
 Do not change the loop or the Convert.ToString() method
var timer = new Stopwatch();
timer.Start();
string result = "";
for (int i = 0; i < 50000; i++)
result += Convert.ToString(i, 2);
Console.WriteLine(result.Length);
Console.WriteLine(timer.Elapsed);
29
Solution: String Concatenation
var timer = new Stopwatch();
timer.Start();
var result = new StringBuilder();
for (int i = 0; i < 50000; i++)
result.Append(Convert.ToString(i, 2));
Console.WriteLine(result.Length);
Console.WriteLine(timer.Elapsed);
Summary
 Strings are immutable sequences of Unicode characters
 String processing methods
 IndexOf(), Compare(), Substring(),
Remove(), ToUpper / ToLower(), Replace(), …
 StringBuilder efficiently builds / modifies strings
30
var result = new StringBuilder();
for (int i = 0; i < 500000; i++) result.Append(i.ToString());
string str = "Hello, C#";
str[2] = 'a'; // Error!
?
Strings and Text Processing
https://softuni.bg/courses/programming-fundamentals
License
 This course (slides, examples, demos, videos, homework, etc.)
is licensed under the "Creative Commons Attribution-
NonCommercial-ShareAlike 4.0 International" license
 Attribution: this work may contain portions from
 "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license
32
Trainings @ Software University
 Software University Foundation – softuni.org
 Software University – High-Quality Education,
Profession and Job for Software Developers
 softuni.bg
 Software University @ Facebook
 facebook.com/SoftwareUniversity
 Software University Forums – forum.softuni.bg

More Related Content

What's hot (20)

PPTX
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
PPTX
16. Arrays Lists Stacks Queues
Intro C# Book
 
PPTX
03. Operators Expressions and statements
Intro C# Book
 
PPTX
05. Conditional Statements
Intro C# Book
 
PPTX
07. Arrays
Intro C# Book
 
PPTX
04. Console Input Output
Intro C# Book
 
PPTX
02. Data Types and variables
Intro C# Book
 
PPTX
12. Exception Handling
Intro C# Book
 
PPTX
19. Data Structures and Algorithm Complexity
Intro C# Book
 
PPTX
15. Streams Files and Directories
Intro C# Book
 
PPTX
19. Java data structures algorithms and complexity
Intro C# Book
 
PPTX
05. Java Loops Methods and Classes
Intro C# Book
 
PPTX
16. Java stacks and queues
Intro C# Book
 
PPTX
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
PPTX
20.1 Java working with abstraction
Intro C# Book
 
PPTX
Java Foundations: Arrays
Svetlin Nakov
 
PPTX
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
PPTX
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
PPTX
Python programming workshop session 1
Abdul Haseeb
 
PPT
Parameters
James Brotsos
 
03 and 04 .Operators, Expressions, working with the console and conditional s...
Intro C# Book
 
16. Arrays Lists Stacks Queues
Intro C# Book
 
03. Operators Expressions and statements
Intro C# Book
 
05. Conditional Statements
Intro C# Book
 
07. Arrays
Intro C# Book
 
04. Console Input Output
Intro C# Book
 
02. Data Types and variables
Intro C# Book
 
12. Exception Handling
Intro C# Book
 
19. Data Structures and Algorithm Complexity
Intro C# Book
 
15. Streams Files and Directories
Intro C# Book
 
19. Java data structures algorithms and complexity
Intro C# Book
 
05. Java Loops Methods and Classes
Intro C# Book
 
16. Java stacks and queues
Intro C# Book
 
Java Foundations: Strings and Text Processing
Svetlin Nakov
 
20.1 Java working with abstraction
Intro C# Book
 
Java Foundations: Arrays
Svetlin Nakov
 
Java Foundations: Basic Syntax, Conditions, Loops
Svetlin Nakov
 
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
Python programming workshop session 1
Abdul Haseeb
 
Parameters
James Brotsos
 

Similar to 13 Strings and Text Processing (20)

PPTX
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
PPT
13 Strings and text processing
maznabili
 
PPTX
String in .net
Larry Nung
 
PDF
LectureNotes-04-DSA
Haitham El-Ghareeb
 
PDF
Module 6 - String Manipulation.pdf
MegMeg17
 
PPT
Csphtp1 15
HUST
 
PDF
C# p6
Renas Rekany
 
PPTX
13string in c#
Sireesh K
 
PPTX
C# String
Raghuveer Guthikonda
 
PDF
OOPs difference faqs- 4
Umar Ali
 
PDF
C# chap 10
Shehrevar Davierwala
 
PPTX
Strings in c#
Dr.Neeraj Kumar Pandey
 
PPTX
C# string concatenations in unity (Updated 2014/7/11)
Sindharta Tanuwijaya
 
PPSX
String and string manipulation x
Shahjahan Samoon
 
PPT
Strings Arrays
phanleson
 
PPTX
Core C# Programming Constructs, Part 1
Vahid Farahmandian
 
PPTX
Strings
Amrutha Rajan
 
PPTX
C# Operators. (C-Sharp Operators)
Abid Kohistani
 
PPTX
The string class
Syed Zaid Irshad
 
PPTX
Cs1123 9 strings
TAlha MAlik
 
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
13 Strings and text processing
maznabili
 
String in .net
Larry Nung
 
LectureNotes-04-DSA
Haitham El-Ghareeb
 
Module 6 - String Manipulation.pdf
MegMeg17
 
Csphtp1 15
HUST
 
13string in c#
Sireesh K
 
OOPs difference faqs- 4
Umar Ali
 
Strings in c#
Dr.Neeraj Kumar Pandey
 
C# string concatenations in unity (Updated 2014/7/11)
Sindharta Tanuwijaya
 
String and string manipulation x
Shahjahan Samoon
 
Strings Arrays
phanleson
 
Core C# Programming Constructs, Part 1
Vahid Farahmandian
 
Strings
Amrutha Rajan
 
C# Operators. (C-Sharp Operators)
Abid Kohistani
 
The string class
Syed Zaid Irshad
 
Cs1123 9 strings
TAlha MAlik
 
Ad

More from Intro C# Book (17)

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
18. Dictionaries, Hash-Tables and Set
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
 
18. Dictionaries, Hash-Tables and Set
Intro C# Book
 
17. Trees and Tree Like Structures
Intro C# Book
 
14 Defining Classes
Intro C# Book
 
Ad

Recently uploaded (20)

PPTX
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
PPTX
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PDF
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PPTX
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
PPTX
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
PPTX
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
PPTX
本科硕士学历佛罗里达大学毕业证(UF毕业证书)24小时在线办理
Taqyea
 
PPTX
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPTX
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
PDF
DevOps Design for different deployment options
henrymails
 
PDF
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
Orchestrating things in Angular application
Peter Abraham
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
法国巴黎第二大学本科毕业证{Paris 2学费发票Paris 2成绩单}办理方法
Taqyea
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
Build Fast, Scale Faster: Milvus vs. Zilliz Cloud for Production-Ready AI
Zilliz
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
Research Design - Report on seminar in thesis writing. PPTX
arvielobos1
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
Lec15_Mutability Immutability-converted.pptx
khanjahanzaib1
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
INTEGRATION OF ICT IN LEARNING AND INCORPORATIING TECHNOLOGY
kvshardwork1235
 
本科硕士学历佛罗里达大学毕业证(UF毕业证书)24小时在线办理
Taqyea
 
西班牙武康大学毕业证书{UCAMOfferUCAM成绩单水印}原版制作
Taqyea
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
unit 2_2 copy right fdrgfdgfai and sm.pptx
nepmithibai2024
 
DevOps Design for different deployment options
henrymails
 
Azure_DevOps introduction for CI/CD and Agile
henrymails
 

13 Strings and Text Processing

  • 1. Strings and Text Processing Processing and Manipulating Text Using the .NET String Class SoftUni Team Technical Trainers Software University http://softuni.bg
  • 2. Table of Contents 1. What is a String? 2. Manipulating Strings  Comparing, Concatenating, Searching  Extracting Substrings, Splitting 3. Building and Modifying Strings  Why Is the + Operator Slow?  Using the StringBuilder Class 2
  • 5. 5  Strings are sequences of characters (texts)  The string data type in C#  Declared by the string keyword  Maps to System.String .NET data type  Strings are enclosed in quotes:  Concatenated using the "+" operator: Strings string s = "Hello, C#"; string s = "Hello" + " " + "C#";
  • 6. 6  Strings are immutable (read-only) sequences of characters  Accessible by index (read-only)  Strings use Unicode (can use most alphabets, e.g. Arabic) In C# Strings are Immutable, use Unicode string str = "Hello, C#"; let ch = str[2]; // OK str[2] = 'a'; // Error! string greeting = "ْ‫م‬ُ‫ك‬ْ‫ي‬‫ا‬‫ل‬‫ا‬‫ع‬ ُ‫م‬‫ا‬‫َل‬َّ‫;"الس‬ // As-salamu alaykum 0 1 2 3 4 5 6 7 8 H e l l o , C # index = str[index] =
  • 7. 7  Initializing from a string literal:  Reading a string from the console:  Converting a string from and to a char array: Initializing a String string str = "Hello, C#"; string name = Console.ReadLine(); Console.WriteLine("Hi, " + name); string str = new String(new char[] {'s', 't', 'r'}); char[] charArr = str.ToCharArray(); // ['s', 't', 'r'] 0 1 2 3 4 5 6 7 8 H e l l o , C #
  • 8. Manipulating Strings Comparing, Concatenating, Searching, Extracting Substrings, Splitting
  • 9. 9  Ordinal (exact binary) string comparison  Case-insensitive string comparison  Case-sensitive string comparison Comparing Strings int result = string.Compare(str1, str2, true); // result == 0 if str1 equals str2 // result < 0 if str1 is before str2 // result > 0 if str1 is after str2 int result = string.Compare(str1, str2, false); int eq = (str1 == str2); // uses String.Equals(…)
  • 10. Concatenating (Combining) Strings  Use the Concat() method  Use the + or the += operators  Any object can be appended to a string string str = string.Concat(str1, str2); string str = str1 + str2 + str3; string str += str1; string name = "Peter"; int age = 22; string s = name + " " + age; //  "Peter 22" 10
  • 11. 11  Finding a substring within a given string  str.IndexOf(string term) – returns the first index or -1  str.LastIndexOf(string term) – finds the last occurence Searching in Strings string email = "[email protected]"; int firstIndex = email.IndexOf("@"); // 5 int secondIndex = email.IndexOf("a", 2); // 8 int notFound = email.IndexOf("/"); // -1 string verse = "To be or not to be…"; int lastIndex = verse.LastIndexOf("be"); // 16
  • 12. 12 Problem: Count Substring Occurrences  You are given a text and a pattern  Find how many times that pattern occurs in the text  Overlapping is allowed Welcome to SoftUni Java 0 ababa caba aba 3 aaaaaa aa 5 Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/320#1
  • 13. 13 Solution: Count Substring Occurrences string input = Console.ReadLine().ToLower(); string pattern = Console.ReadLine().ToLower(); int counter = 0; int index = input.IndexOf(pattern); while (index != -1) { counter++; index = input.IndexOf(pattern, index + 1) } Console.WriteLine(counter);
  • 14. Extracting Substrings  str.Substring(int startIndex, int length)  str.Substring(int startIndex) string filename = @"C:PicsRila2017.jpg"; string name = filename.Substring(8, 8); // name == "Rila2017" string filename = @"C:PicsRila2017.jpg"; string nameAndExtension = filename.Substring(8); // nameAndExtension == "Rila2017.jpg" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 C : P i c s R i l a 2 0 1 7 . j p g 14
  • 15. Splitting Strings  Split a string by given separator(s) :  Example: string[] Split(params char[] separator) string listOfBeers = "Amstel, Zagorka, Tuborg, Becks."; string[] beers = listOfBeers.Split(' ', ',', '.'); Console.WriteLine("Available beers are:"); foreach (string beer in beers) Console.WriteLine(beer); 15
  • 16. Other String Operations Replacing and Deleting Substrings, Changing Character Casing, Trimming
  • 17. Replacing and Deleting Substrings  str.Replace(match, replacement) – replaces all occurrences  The result is a new string (strings are immutable)  str.Remove(int index, int length) – deletes part of a string  Produces a new string as result string cocktail = "Vodka + Martini + Cherry"; string replaced = cocktail.Replace("+", "and"); // Vodka and Martini and Cherry string price = "$ 1234567"; string lowPrice = price.Remove(2, 3); // $ 4567 17
  • 18. 18 Problem: Text Filter (Banned Words)  You are given a text and a string of banned words  Replace all banned words in the text with asterisks  Replace with asterisks (*), whose count is equal to the word's length Linux, Windows It is not Linux, it is GNU/Linux. Linux is merely the kernel, while GNU adds the functionality... Check your solution here: https://judge.softuni.bg/Contests/Practice/Index/320#2 It is not *****, it is GNU/*****. ***** is merely the kernel, while GNU adds the functionality...
  • 19. 19 Solution: Text Filter string[] banWords = Console.ReadLine() .Split(…); // TODO: add separators string text = Console.ReadLine(); foreach (var banWord in banWords) { if (text.Contains(banWord)) { text = text.Replace(banWord, new string('*', banWord.Length)); } } Console.WriteLine(text); Contains(…) checks if string contains another string Replace a word with a sequence of asterisks of the same length
  • 20. Changing Character Casing  Using the method ToLower()  Using the method ToUpper() string alpha = "aBcDeFg"; string lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha); string alpha = "aBcDeFg"; string upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha); 20
  • 21. 21  str.Trim() – trims whitespaces at start and end of string  str.Trim(params char[] chars)  str.TrimStart() and str.TrimEnd() Trimming White Space string s = " example of white space "; string clean = s.Trim(); Console.WriteLine(clean); // example of white space string s = " tnHello!!! n"; string clean = s.Trim(' ', ',' ,'!', 'n','t'); Console.WriteLine(clean); // Hello string s = " C# "; string clean = s.TrimStart(); // clean = "C# "
  • 22. Live Exercises in Class (Lab) String Operations
  • 23. Building and Modifying Strings Using the StringBuilder Class
  • 24. StringBuilder: How It Works?  StringBuilder keeps a buffer space, allocated in advance  Do not allocate memory for most operations  performance H e l l o , C # !StringBuilder: Length = 9 Capacity = 15 Capacity used buffer (Length) unused buffer 24
  • 25. 25  Use the System.Text.StringBuilder to build / modify strings: Changing the Contents of a String public static string ReverseString(string str) { StringBuilder sb = new StringBuilder(); for (int i = str.Length - 1; i >= 0; i--) { sb.Append(str[i]); } return sb.ToString(); }
  • 26. The StringBuilder Class  StringBuilder(int capacity) constructor allocates in advance buffer of size capacity  Capacity holds the currently allocated space (in characters)  Length holds the length of the string in the buffer  this[int index] (indexer) access the char at given position 26 H e l l o , C # ! Capacity used buffer (Length) unused buffer
  • 27. 27 StringBuilder Operations – Examples var builder = new StringBuilder(100); builder.Append("Hello Maria, how are you?"); Console.WriteLine(builder); // Hello Maria, how are you? builder[6] = 'D'; Console.WriteLine(builder); // Hello Daria, how are you? builder.Remove(5, 6); Console.WriteLine(builder); // Hello, how are you? builder.Insert(5, " Peter"); Console.WriteLine(builder); // Hello Peter, how are you? builder.Replace("Peter", "George"); Console.WriteLine(builder); // Hello George, how are you?
  • 28. 28 Problem: String Concatenation  Given the code below try to optimize it to go under a second  Do not change the loop or the Convert.ToString() method var timer = new Stopwatch(); timer.Start(); string result = ""; for (int i = 0; i < 50000; i++) result += Convert.ToString(i, 2); Console.WriteLine(result.Length); Console.WriteLine(timer.Elapsed);
  • 29. 29 Solution: String Concatenation var timer = new Stopwatch(); timer.Start(); var result = new StringBuilder(); for (int i = 0; i < 50000; i++) result.Append(Convert.ToString(i, 2)); Console.WriteLine(result.Length); Console.WriteLine(timer.Elapsed);
  • 30. Summary  Strings are immutable sequences of Unicode characters  String processing methods  IndexOf(), Compare(), Substring(), Remove(), ToUpper / ToLower(), Replace(), …  StringBuilder efficiently builds / modifies strings 30 var result = new StringBuilder(); for (int i = 0; i < 500000; i++) result.Append(i.ToString()); string str = "Hello, C#"; str[2] = 'a'; // Error!
  • 31. ? Strings and Text Processing https://softuni.bg/courses/programming-fundamentals
  • 32. License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA license 32
  • 33. Trainings @ Software University  Software University Foundation – softuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg  Software University @ Facebook  facebook.com/SoftwareUniversity  Software University Forums – forum.softuni.bg

Editor's Notes

  • #9: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #17: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #26: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*
  • #31: (c) 2007 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.*