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

PPTX
09. Java Methods
PPTX
13. Java text processing
PPTX
Chapter 22. Lambda Expressions and LINQ
PPTX
07. Java Array, Set and Maps
PPTX
10. Recursion
PPTX
06.Loops
PPTX
02. Primitive Data Types and Variables
PPTX
09. Methods
09. Java Methods
13. Java text processing
Chapter 22. Lambda Expressions and LINQ
07. Java Array, Set and Maps
10. Recursion
06.Loops
02. Primitive Data Types and Variables
09. Methods

What's hot (20)

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

Similar to 13 Strings and Text Processing (20)

PPTX
16 strings-and-text-processing-120712074956-phpapp02
PPT
13 Strings and text processing
PPTX
String in .net
PDF
LectureNotes-04-DSA
PDF
Module 6 - String Manipulation.pdf
PPT
Csphtp1 15
PDF
PPTX
13string in c#
PPTX
PDF
OOPs difference faqs- 4
PDF
PPTX
Strings in c#
PPTX
C# string concatenations in unity (Updated 2014/7/11)
PPSX
String and string manipulation x
PPT
Strings Arrays
PPTX
Core C# Programming Constructs, Part 1
PPTX
Strings
PPTX
C# Operators. (C-Sharp Operators)
PPTX
The string class
PPTX
Cs1123 9 strings
16 strings-and-text-processing-120712074956-phpapp02
13 Strings and text processing
String in .net
LectureNotes-04-DSA
Module 6 - String Manipulation.pdf
Csphtp1 15
13string in c#
OOPs difference faqs- 4
Strings in c#
C# string concatenations in unity (Updated 2014/7/11)
String and string manipulation x
Strings Arrays
Core C# Programming Constructs, Part 1
Strings
C# Operators. (C-Sharp Operators)
The string class
Cs1123 9 strings
Ad

More from Intro C# Book (17)

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

Recently uploaded (20)

PPTX
522797556-Unit-2-Temperature-measurement-1-1.pptx
PDF
The Internet -By the Numbers, Sri Lanka Edition
PDF
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
PPTX
Job_Card_System_Styled_lorem_ipsum_.pptx
PDF
www-codemechsolutions-com-whatwedo-cloud-application-migration-services.pdf
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PDF
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
PDF
Testing WebRTC applications at scale.pdf
PDF
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
PDF
Decoding a Decade: 10 Years of Applied CTI Discipline
PPTX
durere- in cancer tu ttresjjnklj gfrrjnrs mhugyfrd
PPTX
Digital Literacy And Online Safety on internet
PDF
Tenda Login Guide: Access Your Router in 5 Easy Steps
PPTX
nagasai stick diagrams in very large scale integratiom.pptx
PPTX
Internet___Basics___Styled_ presentation
PPTX
CSharp_Syntax_Basics.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxx
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
PDF
Unit-1 introduction to cyber security discuss about how to secure a system
PPTX
Module 1 - Cyber Law and Ethics 101.pptx
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
522797556-Unit-2-Temperature-measurement-1-1.pptx
The Internet -By the Numbers, Sri Lanka Edition
LABUAN4D EXCLUSIVE SERVER STAR GAMING ASIA NO.1
Job_Card_System_Styled_lorem_ipsum_.pptx
www-codemechsolutions-com-whatwedo-cloud-application-migration-services.pdf
An introduction to the IFRS (ISSB) Stndards.pdf
Behind the Smile Unmasking Ken Childs and the Quiet Trail of Deceit Left in H...
Testing WebRTC applications at scale.pdf
Vigrab.top – Online Tool for Downloading and Converting Social Media Videos a...
Decoding a Decade: 10 Years of Applied CTI Discipline
durere- in cancer tu ttresjjnklj gfrrjnrs mhugyfrd
Digital Literacy And Online Safety on internet
Tenda Login Guide: Access Your Router in 5 Easy Steps
nagasai stick diagrams in very large scale integratiom.pptx
Internet___Basics___Styled_ presentation
CSharp_Syntax_Basics.pptxxxxxxxxxxxxxxxxxxxxxxxxxxxx
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
Unit-1 introduction to cyber security discuss about how to secure a system
Module 1 - Cyber Law and Ethics 101.pptx
Introduction about ICD -10 and ICD11 on 5.8.25.pptx

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.*