SlideShare a Scribd company logo
Strings andTextStrings andText
ProcessingProcessing
Processing and ManipulatingText InformationProcessing and ManipulatingText Information
Svetlin NakovSvetlin Nakov
Telerik CorporationTelerik Corporation
www.telerik.comwww.telerik.com
Table of ContentsTable of Contents
1.1. What is String?What is String?
2.2. Creating and Using StringsCreating and Using Strings
 Declaring, Creating, Reading and PrintingDeclaring, Creating, Reading and Printing
1.1. Manipulating StringsManipulating Strings
 Comparing, Concatenating, Searching,Comparing, Concatenating, Searching,
Extracting Substrings, SplittingExtracting Substrings, Splitting
1.1. Other String OperationsOther String Operations
 Replacing Substrings, Deleting Substrings,Replacing Substrings, Deleting Substrings,
Changing Character Casing, TrimmingChanging Character Casing, Trimming
Table of Contents (2)Table of Contents (2)
5.5. Building and Modifying StringsBuilding and Modifying Strings
 UsingUsing StringBuilderStringBuilder ClassClass
5.5. Formatting StringsFormatting Strings
What Is String?What Is String?
What Is String?What Is String?
 Strings are sequences of charactersStrings are sequences of characters
 Each character is a Unicode symbolEach character is a Unicode symbol
 Represented by theRepresented by the stringstring data type in C#data type in C#
((System.StringSystem.String))
 Example:Example:
string s = "Hello, C#";string s = "Hello, C#";
HH ee ll ll oo ,, CC ##ss
TheThe System.StringSystem.String ClassClass
 Strings are represented byStrings are represented by System.StringSystem.String
objects in .NET Frameworkobjects in .NET Framework
String objects contain an immutable (read-only)String objects contain an immutable (read-only)
sequence of characterssequence of characters
Strings use Unicode in to support multipleStrings use Unicode in to support multiple
languages and alphabetslanguages and alphabets
 Strings are stored in the dynamic memoryStrings are stored in the dynamic memory
((managed heapmanaged heap))
 System.StringSystem.String is reference typeis reference type
TheThe System.StringSystem.String Class (2)Class (2)
 String objects are like arrays of charactersString objects are like arrays of characters
((char[]char[]))
Have fixed length (Have fixed length (String.LengthString.Length))
Elements can be accessed directly by indexElements can be accessed directly by index
 The index is in the range [The index is in the range [00......Length-1Length-1]]
string s = "Hello!";string s = "Hello!";
int len = s.Length; // len = 6int len = s.Length; // len = 6
char ch = s[1]; // ch = 'e'char ch = s[1]; // ch = 'e'
00 11 22 33 44 55
HH ee ll ll oo !!
index =index =
s[index] =s[index] =
Strings – First ExampleStrings – First Example
static void Main()static void Main()
{{
string s =string s =
"Stand up, stand up, Balkan Superman.";"Stand up, stand up, Balkan Superman.";
Console.WriteLine("s = "{0}"", s);Console.WriteLine("s = "{0}"", s);
Console.WriteLine("s.Length = {0}", s.Length);Console.WriteLine("s.Length = {0}", s.Length);
for (int i = 0; i < s.Length; i++)for (int i = 0; i < s.Length; i++)
{{
Console.WriteLine("s[{0}] = {1}", i, s[i]);Console.WriteLine("s[{0}] = {1}", i, s[i]);
}}
}}
Strings – First ExampleStrings – First Example
Live DemoLive Demo
Creating and Using StringsCreating and Using Strings
Declaring, Creating, Reading and PrintingDeclaring, Creating, Reading and Printing
Declaring StringsDeclaring Strings
 There are two ways of declaring stringThere are two ways of declaring string
variables:variables:
UsingUsing thethe C#C# keywordkeyword stringstring
Using the .NET's fully qualified class nameUsing the .NET's fully qualified class name
System.StringSystem.String
The above three declarations are equivalentThe above three declarations are equivalent
string str1;string str1;
System.String str2;System.String str2;
String str3;String str3;
Creating StringsCreating Strings
 Before initializing a string variable hasBefore initializing a string variable has nullnull
valuevalue
 Strings can be initialized by:Strings can be initialized by:
Assigning a string literal to the string variableAssigning a string literal to the string variable
Assigning the value of another string variableAssigning the value of another string variable
Assigning the result of operation of type stringAssigning the result of operation of type string
Creating Strings (2)Creating Strings (2)
 Not initialized variables has value ofNot initialized variables has value of nullnull
 Assigning a string literalAssigning a string literal
 Assigning from another string variableAssigning from another string variable
 Assigning from the result of string operationAssigning from the result of string operation
string s; // s is equal to nullstring s; // s is equal to null
string s = "I am a string literal!";string s = "I am a string literal!";
string s2 = s;string s2 = s;
string s = 42.ToString();string s = 42.ToString();
Reading and Printing StringsReading and Printing Strings
 Reading strings from the consoleReading strings from the console
Use the methodUse the method Console.Console.ReadLine()ReadLine()
string s = Console.ReadLine();string s = Console.ReadLine();
Console.Write("Please enter your name: ");Console.Write("Please enter your name: ");
string name = Console.ReadLine();string name = Console.ReadLine();
Console.Write("Hello, {0}! ", name);Console.Write("Hello, {0}! ", name);
Console.WriteLine("Welcome to our party!");Console.WriteLine("Welcome to our party!");
 Printing strings to the consolePrinting strings to the console
 Use the methodsUse the methods Write()Write() andand WriteLine()WriteLine()
Reading and Printing StringsReading and Printing Strings
Live DemoLive Demo
Comparing, Concatenating, Searching,Comparing, Concatenating, Searching,
Extracting Substrings, SplittingExtracting Substrings, Splitting
Manipulating StringsManipulating Strings
Comparing StringsComparing Strings
 A number of ways exist to compare twoA number of ways exist to compare two
strings:strings:
Dictionary-based string comparisonDictionary-based string comparison
 Case-insensitiveCase-insensitive
 Case-sensitiveCase-sensitive
int result = string.Compare(str1, str2, true);int result = string.Compare(str1, str2, true);
// result == 0 if str1 equals str2// result == 0 if str1 equals str2
// result < 0 if str1 if before str2// result < 0 if str1 if before str2
// result > 0 if str1 if after str2// result > 0 if str1 if after str2
string.Compare(str1, str2, false);string.Compare(str1, str2, false);
Comparing Strings (2)Comparing Strings (2)
 Equality checking by operatorEquality checking by operator ====
Performs case-sensitive comparePerforms case-sensitive compare
 Using the case-sensitiveUsing the case-sensitive Equals()Equals() methodmethod
The same effect like the operatorThe same effect like the operator ====
if (str1 == str2)if (str1 == str2)
{{
……
}}
if (str1.Equals(str2))if (str1.Equals(str2))
{{
……
}}
Comparing Strings – ExampleComparing Strings – Example
 Finding the first string in a lexicographical orderFinding the first string in a lexicographical order
from a given list of strings:from a given list of strings:
string[] towns = {"Sofia", "Varna", "Plovdiv",string[] towns = {"Sofia", "Varna", "Plovdiv",
"Pleven", "Bourgas", "Rousse", "Yambol"};"Pleven", "Bourgas", "Rousse", "Yambol"};
string firstTown = towns[0];string firstTown = towns[0];
for (int i=1; i<towns.Length; i++)for (int i=1; i<towns.Length; i++)
{{
string currentTown = towns[i];string currentTown = towns[i];
if (String.Compare(currentTown, firstTown) < 0)if (String.Compare(currentTown, firstTown) < 0)
{{
firstTown = currentTown;firstTown = currentTown;
}}
}}
Console.WriteLine("First town: {0}", firstTown);Console.WriteLine("First town: {0}", firstTown);
Live DemoLive Demo
Comparing StringsComparing Strings
Concatenating StringsConcatenating Strings
 There are two ways to combine strings:There are two ways to combine strings:
 Using theUsing the Concat()Concat() methodmethod
 Using theUsing the ++ or theor the +=+= operatorsoperators
 Any object can be appended to stringAny object can be appended to string
string str = String.Concat(str1, str2);string str = String.Concat(str1, str2);
string str = str1 + str2 + str3;string str = str1 + str2 + str3;
string str += str1;string str += str1;
string name = "Peter";string name = "Peter";
int age = 22;int age = 22;
string s = name + " " + age; //string s = name + " " + age; //  "Peter 22""Peter 22"
Concatenating Strings –Concatenating Strings –
ExampleExample
string firstName = "Svetlin";string firstName = "Svetlin";
string lastName = "Nakov";string lastName = "Nakov";
string fullName = firstName + " " + lastName;string fullName = firstName + " " + lastName;
Console.WriteLine(fullName);Console.WriteLine(fullName);
// Svetlin Nakov// Svetlin Nakov
int age = 25;int age = 25;
string nameAndAge =string nameAndAge =
"Name: " + fullName +"Name: " + fullName +
"nAge: " + age;"nAge: " + age;
Console.WriteLine(nameAndAge);Console.WriteLine(nameAndAge);
// Name: Svetlin Nakov// Name: Svetlin Nakov
// Age: 25// Age: 25
Live Demo
Concatenating StringsConcatenating Strings
Searching in StringsSearching in Strings
 Finding a character or substring within givenFinding a character or substring within given
stringstring
 First occurrenceFirst occurrence
 First occurrence starting at given positionFirst occurrence starting at given position
 Last occurrenceLast occurrence
IndexOf(string str)IndexOf(string str)
IndexOf(string str, int startIndex)IndexOf(string str, int startIndex)
LastIndexOf(string)LastIndexOf(string)
Searching in Strings – ExampleSearching in Strings – Example
string str = "C# Programming Course";string str = "C# Programming Course";
int index = str.IndexOf("C#"); // index = 0int index = str.IndexOf("C#"); // index = 0
index = str.IndexOf("Course"); // index = 15index = str.IndexOf("Course"); // index = 15
index = str.IndexOf("COURSE"); // index = -1index = str.IndexOf("COURSE"); // index = -1
// IndexOf is case-sensetive. -1 means not found// IndexOf is case-sensetive. -1 means not found
index = str.IndexOf("ram"); // index = 7index = str.IndexOf("ram"); // index = 7
index = str.IndexOf("r"); // index = 4index = str.IndexOf("r"); // index = 4
index = str.IndexOf("r", 5); // index = 7index = str.IndexOf("r", 5); // index = 7
index = str.IndexOf("r", 8); // index = 18index = str.IndexOf("r", 8); // index = 18
00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 ……
CC ## PP rr oo gg rr aa mm mm ii nn gg ……
index =index =
s[index] =s[index] =
Live DemoLive Demo
SearchingSearching
in Stringsin Strings
Extracting SubstringsExtracting Substrings
 Extracting substringsExtracting substrings
 str.Substring(int startIndex, int length)str.Substring(int startIndex, int length)
 str.Substring(int startIndex)str.Substring(int startIndex)
string filename = @"C:PicsRila2009.jpg";string filename = @"C:PicsRila2009.jpg";
string name = filename.Substring(8, 8);string name = filename.Substring(8, 8);
// name is Rila2009// name is Rila2009
string filename = @"C:PicsSummer2009.jpg";string filename = @"C:PicsSummer2009.jpg";
string nameAndExtension = filename.Substring(8);string nameAndExtension = filename.Substring(8);
// nameAndExtension is Summer2009.jpg// nameAndExtension is Summer2009.jpg
00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717 1818 1919
CC ::  PP ii cc ss  RR ii ll aa 22 00 00 55 .. jj pp gg
Live DemoLive Demo
Extracting SubstringsExtracting Substrings
Splitting StringsSplitting Strings
 To split a string by given separator(s) use theTo split a string by given separator(s) use the
following method:following method:
 Example:Example:
string[] Split(params char[])string[] Split(params char[])
string listOfBeers =string listOfBeers =
"Amstel, Zagorka, Tuborg, Becks.";"Amstel, Zagorka, Tuborg, Becks.";
string[] beers =string[] beers =
listOfBeers.Split(' ', ',', '.');listOfBeers.Split(' ', ',', '.');
Console.WriteLine("Available beers are:");Console.WriteLine("Available beers are:");
foreach (string beer in beers)foreach (string beer in beers)
{{
Console.WriteLine(beer);Console.WriteLine(beer);
}}
Live DemoLive Demo
Splitting StringsSplitting Strings
Other String OperationsOther String Operations
Replacing Substrings, Deleting Substrings,Replacing Substrings, Deleting Substrings,
Changing Character Casing, TrimmingChanging Character Casing, Trimming
Replacing and Deleting SubstringsReplacing and Deleting Substrings
 Replace(string,Replace(string, string)string) – replaces all– replaces all
occurrences of given string with anotheroccurrences of given string with another
 The result is new string (strings are immutable)The result is new string (strings are immutable)
 ReRemovemove((indexindex,, lengthlength)) – deletes part of a string– deletes part of a string
and produces new string as resultand produces new string as result
string cocktail = "Vodka + Martini + Cherry";string cocktail = "Vodka + Martini + Cherry";
string replaced = cocktail.Replace("+", "and");string replaced = cocktail.Replace("+", "and");
// Vodka and Martini and Cherry// Vodka and Martini and Cherry
string price = "$ 1234567";string price = "$ 1234567";
string lowPrice = price.Remove(2, 3);string lowPrice = price.Remove(2, 3);
// $ 4567// $ 4567
Changing Character CasingChanging Character Casing
 Using methodUsing method ToLower()ToLower()
 Using methodUsing method ToUpper()ToUpper()
string alpha = "aBcDeFg";string alpha = "aBcDeFg";
string lowerAlpha = alpha.ToLower(); // abcdefgstring lowerAlpha = alpha.ToLower(); // abcdefg
Console.WriteLine(lowerAlpha);Console.WriteLine(lowerAlpha);
string alpha = "aBcDeFg";string alpha = "aBcDeFg";
string upperAlpha = alpha.ToUpper(); // ABCDEFGstring upperAlpha = alpha.ToUpper(); // ABCDEFG
Console.WriteLine(upperAlpha);Console.WriteLine(upperAlpha);
Trimming White SpaceTrimming White Space
 Using methodUsing method Trim()Trim()
 Using methodUsing method Trim(charsTrim(chars))
 UsingUsing TrimTrimStartStart()() andand TrimTrimEndEnd()()
string s = " example of white space ";string s = " example of white space ";
string clean = s.Trim();string clean = s.Trim();
Console.WriteLine(clean);Console.WriteLine(clean);
string s = " tnHello!!! n";string s = " tnHello!!! n";
string clean = s.Trim(' ', ',' ,'!', 'n','t');string clean = s.Trim(' ', ',' ,'!', 'n','t');
Console.WriteLine(clean); // HelloConsole.WriteLine(clean); // Hello
string s = " C# ";string s = " C# ";
string clean = s.TrimStart(); // clean = "C# "string clean = s.TrimStart(); // clean = "C# "
Other String OperationsOther String Operations
Live DemoLive Demo
Building and Modifying StringsBuilding and Modifying Strings
UsingUsing StringBuilderStringBuilder CClasslass
Constructing StringsConstructing Strings
 Strings are immutableStrings are immutable
CConcat()oncat(),, RReplace()eplace(),, TTrim()rim(), ..., ... return newreturn new
string, do not modify the old onestring, do not modify the old one
 Do not use "Do not use "++" for strings in a loop!" for strings in a loop!
It runs very, very inefficiently!It runs very, very inefficiently!
public static string DupChar(char ch, int count)public static string DupChar(char ch, int count)
{{
string result = "";string result = "";
for (int i=0; i<count; i++)for (int i=0; i<count; i++)
result += ch;result += ch;
return result;return result;
}}
Very badVery bad
practice. Avoidpractice. Avoid
this!this!
Slow Building Strings with +Slow Building Strings with +
Live DemoLive Demo
Changing the Contents of a StringChanging the Contents of a String
–– StringBuilderStringBuilder
 Use theUse the System.Text.StringBuilderSystem.Text.StringBuilder class forclass for
modifiable strings of characters:modifiable strings of characters:
 UseUse StringBuilderStringBuilder if you need to keep addingif you need to keep adding
characters to a stringcharacters to a string
public static string ReverseString(string s)public static string ReverseString(string s)
{{
StringBuilder sb = new StringBuilder();StringBuilder sb = new StringBuilder();
for (int i = s.Length-1; i >= 0; i--)for (int i = s.Length-1; i >= 0; i--)
sb.Append(s[i]);sb.Append(s[i]);
return sb.ToString();return sb.ToString();
}}
TheThe StringBuildeStringBuilder Classr Class
 StringBuilderStringBuilder keeps a buffer memory,keeps a buffer memory,
allocated in advanceallocated in advance
Most operations use the buffer memory andMost operations use the buffer memory and
do not allocate new objectsdo not allocate new objects
HH ee ll ll oo ,, CC ## !!StringBuilderStringBuilder::
Length=9Length=9
Capacity=15Capacity=15
CapacityCapacity
used bufferused buffer
(Length)(Length)
unusedunused
bufferbuffer
TheThe StringBuildeStringBuilder Class (2)r Class (2)
 StringBuilder(int capacity)StringBuilder(int capacity) constructorconstructor
allocates in advance buffer memory of a givenallocates in advance buffer memory of a given
sizesize
 By default 16 characters are allocatedBy default 16 characters are allocated
 CapacityCapacity holds the currently allocated space (inholds the currently allocated space (in
characters)characters)
 this[int index]this[int index] (indexer in C#) gives access(indexer in C#) gives access
to the char value at given positionto the char value at given position
 LengthLength holds the length of the string in theholds the length of the string in the
bufferbuffer
TheThe StringBuildeStringBuilder Class (3)r Class (3)
 Append(…)Append(…) appends string or another object after theappends string or another object after the
last character in the bufferlast character in the buffer
 RemoveRemove(int start(int startIndexIndex,, intint lengthlength)) removesremoves
the characters in given rangethe characters in given range
 IInsert(intnsert(int indexindex,, sstring str)tring str) inserts giveninserts given
string (or object) at given positionstring (or object) at given position
 Replace(string oldStr,Replace(string oldStr, string newStr)string newStr)
replaces all occurrences of a substring with new stringreplaces all occurrences of a substring with new string
 TToString()oString() converts theconverts the StringBuilderStringBuilder toto StringString
StringBuilderStringBuilder – Example– Example
 Extracting all capital letters from a stringExtracting all capital letters from a string
public static string ExtractCapitals(string s)public static string ExtractCapitals(string s)
{{
StringBuilder result = new StringBuilder();StringBuilder result = new StringBuilder();
for (int i = 0; i<s.Length; i++)for (int i = 0; i<s.Length; i++)
{{
if (Char.IsUpper(s[i]))if (Char.IsUpper(s[i]))
{{
result.Append(s[i]);result.Append(s[i]);
}}
}}
return result.ToString();return result.ToString();
}}
How theHow the ++ Operator Does StringOperator Does String
Concatenations?Concatenations?
 Consider following string concatenation:Consider following string concatenation:
 It is equivalent to this code:It is equivalent to this code:
 Actually several new objects are created andActually several new objects are created and
leaved to the garbage collectorleaved to the garbage collector
 What happens when usingWhat happens when using ++ in a loop?in a loop?
string result = str1 + str2;string result = str1 + str2;
StringBuilder sb = new StringBuilder();StringBuilder sb = new StringBuilder();
sb.Append(str1);sb.Append(str1);
sb.Append(str2);sb.Append(str2);
string result = sb.ToString();string result = sb.ToString();
UsingUsing StringBuilderStringBuilder
Live DemoLive Demo
Formatting StringsFormatting Strings
UsingUsing ToString()ToString() andand String.Format()String.Format()
MethodMethod ToString()ToString()
 All classes have public virtual methodAll classes have public virtual method
ToString()ToString()
Returns a human-readable, culture-sensitiveReturns a human-readable, culture-sensitive
string representing the objectstring representing the object
Most .NET Framework types have ownMost .NET Framework types have own
implementation ofimplementation of ToString()ToString()
 intint,, floatfloat,, boolbool,, DateTimeDateTime
int number = 5;int number = 5;
string s = "The number is " + number.ToString();string s = "The number is " + number.ToString();
Console.WriteLine(s); // The number is 5Console.WriteLine(s); // The number is 5
MethodMethod ToString(formatToString(format))
 We can apply specific formatting whenWe can apply specific formatting when
converting objects to stringconverting objects to string
 ToString(foToString(forrmatString)matString) methodmethod
int number = 42;int number = 42;
string s = number.ToString("D5"); // 00042string s = number.ToString("D5"); // 00042
s = number.ToString("X"); // 2As = number.ToString("X"); // 2A
// Consider the default culture is Bulgarian// Consider the default culture is Bulgarian
s = number.ToString("C"); // 42,00 лвs = number.ToString("C"); // 42,00 лв
double d = 0.375;double d = 0.375;
s = d.ToString("P2"); // 37,50 %s = d.ToString("P2"); // 37,50 %
Formatting StringsFormatting Strings
 The formatting strings are different for theThe formatting strings are different for the
different typesdifferent types
 Some formatting strings for numbers:Some formatting strings for numbers:
 DD – number (for integer types)– number (for integer types)
 CC – currency (according to current culture)– currency (according to current culture)
 EE – number in exponential notation– number in exponential notation
 PP – percentage– percentage
 XX – hexadecimal number– hexadecimal number
 FF – fixed point (for real numbers)– fixed point (for real numbers)
MethodMethod String.Format()String.Format()
 AppliesApplies templatestemplates for formatting stringsfor formatting strings
Placeholders are used for dynamic textPlaceholders are used for dynamic text
LikeLike Console.WriteLine(…)Console.WriteLine(…)
string template = "If I were {0}, I would {1}.";string template = "If I were {0}, I would {1}.";
string sentence1 = String.Format(string sentence1 = String.Format(
template, "developer", "know C#");template, "developer", "know C#");
Console.WriteLine(sentence1);Console.WriteLine(sentence1);
// If I were developer, I would know C#.// If I were developer, I would know C#.
string sentence2 = String.Format(string sentence2 = String.Format(
template, "elephant", "weigh 4500 kg");template, "elephant", "weigh 4500 kg");
Console.WriteLine(sentence2);Console.WriteLine(sentence2);
// If I were elephant, I would weigh 4500 kg.// If I were elephant, I would weigh 4500 kg.
Composite FormattingComposite Formatting
 The placeholders in the composite formattingThe placeholders in the composite formatting
strings are specified as follows:strings are specified as follows:
 Examples:Examples:
{index[,alignment][:formatString]}{index[,alignment][:formatString]}
double d = 0.375;double d = 0.375;
s = String.Format("{0,10:F5}", d);s = String.Format("{0,10:F5}", d);
// s = " 0,37500"// s = " 0,37500"
int number = 42;int number = 42;
Console.WriteLine("Dec {0:D} = Hex {1:X}",Console.WriteLine("Dec {0:D} = Hex {1:X}",
number, number);number, number);
// Dec 42 = Hex 2A// Dec 42 = Hex 2A
Formatting DatesFormatting Dates
 Dates have their own formatting stringsDates have their own formatting strings
dd,, dddd –– day (with/without leading zero)day (with/without leading zero)
MM,, MMMM –– monthmonth
yyyy,, yyyyyyyy –– year (2 or 4 digits)year (2 or 4 digits)
hh,, HHHH,, mm,, mmmm,, ss,, ssss –– hour, minute, secondhour, minute, second
DateTime now = DateTime.Now;DateTime now = DateTime.Now;
Console.WriteLine(Console.WriteLine(
"Now is {0:d.MM.yyyy HH:mm:ss}", now);"Now is {0:d.MM.yyyy HH:mm:ss}", now);
// Now is 31.11.2009 11:30:32// Now is 31.11.2009 11:30:32
Formatting StringsFormatting Strings
Live DemoLive Demo
SummarySummary
 Strings are immutable sequences of charactersStrings are immutable sequences of characters
(instances of(instances of System.StringSystem.String))
 Declared by the keywordDeclared by the keyword stringstring in C#in C#
 Can be initialized by string literalsCan be initialized by string literals
 Most important string processing members are:Most important string processing members are:
 LengthLength,, this[]this[],, Compare(str1,Compare(str1, str2)str2),,
IndexOf(str)IndexOf(str),, LastIndexOf(str)LastIndexOf(str),,
Substring(startIndex,Substring(startIndex, length)length),,
Replace(oldStr,Replace(oldStr, newStr)newStr),,
Remove(startIndex,Remove(startIndex, length)length),, ToLower()ToLower(),,
ToUpper()ToUpper(),, Trim()Trim()
Summary (2)Summary (2)
 Objects can be converted to strings and can beObjects can be converted to strings and can be
formatted in different styles (usingformatted in different styles (using
ToStringToString()() method)method)
 Strings can be constructed by usingStrings can be constructed by using
placeholders and formatting stringsplaceholders and formatting strings
((String.FormatString.Format(…)(…)))
Strings and Text ProcessingStrings and Text Processing
Questions?Questions?
http://academy.telerik.com
ExercisesExercises
1.1. Describe the strings in C#. What is typical for theDescribe the strings in C#. What is typical for the
stringstring data type? Describe the most importantdata type? Describe the most important
methods of themethods of the StringString class.class.
2.2. Write a program that reads a string, reverses it andWrite a program that reads a string, reverses it and
prints it on the console. Example: "sample"prints it on the console. Example: "sample" 
""elpmaselpmas".".
3.3. Write a program to check if in a given expression theWrite a program to check if in a given expression the
brackets are put correctly. Example of correctbrackets are put correctly. Example of correct
expression:expression: ((a+b)/5-d)((a+b)/5-d). Example of incorrect. Example of incorrect
expression:expression: )(a+b)))(a+b))..
Exercises (2)Exercises (2)
4.4. Write a program that finds how many times aWrite a program that finds how many times a
substring is contained in a given text (perform casesubstring is contained in a given text (perform case
insensitive search).insensitive search).
Example: The target substring is "Example: The target substring is "inin". The text". The text
is as follows:is as follows:
The result is: 9.The result is: 9.
We are living in an yellow submarine. We don'tWe are living in an yellow submarine. We don't
have anything else. Inside the submarine is veryhave anything else. Inside the submarine is very
tight. So we are drinking all the day. We willtight. So we are drinking all the day. We will
move out of it in 5 days.move out of it in 5 days.
Exercises (3)Exercises (3)
5.5. You are given a text. Write a program that changesYou are given a text. Write a program that changes
the text in all regions surrounded by the tagsthe text in all regions surrounded by the tags
<upcase><upcase> andand </upcase></upcase> to uppercase. The tagsto uppercase. The tags
cannot be nested. Example:cannot be nested. Example:
The expected result:The expected result:
We are living in a <upcase>yellowWe are living in a <upcase>yellow
submarine</upcase>. We don't havesubmarine</upcase>. We don't have
<upcase>anything</upcase> else.<upcase>anything</upcase> else.
We are living in a YELLOW SUBMARINE. We don't haveWe are living in a YELLOW SUBMARINE. We don't have
ANYTHING else.ANYTHING else.
Exercises (4)Exercises (4)
6.6. Write a program that reads from the console a stringWrite a program that reads from the console a string
of maximum 20 characters. If the length of the stringof maximum 20 characters. If the length of the string
is less than 20, the rest of the characters should beis less than 20, the rest of the characters should be
filled with '*'. Print the result string into the console.filled with '*'. Print the result string into the console.
7.7. Write a program that encodes and decodes a stringWrite a program that encodes and decodes a string
using given encryption key (cipher). The key consistsusing given encryption key (cipher). The key consists
of a sequence of characters. The encoding/decodingof a sequence of characters. The encoding/decoding
is done by performing XOR (exclusive or) operationis done by performing XOR (exclusive or) operation
over the first letter of the string with the first of theover the first letter of the string with the first of the
key, the second – with the second, etc. When thekey, the second – with the second, etc. When the
last key character is reached, the next is the first.last key character is reached, the next is the first.
Exercises (5)Exercises (5)
8.8. Write a program that extracts from a given text allWrite a program that extracts from a given text all
sentences containing given word.sentences containing given word.
Example: The word is "Example: The word is "inin". The text is:". The text is:
The expected result is:The expected result is:
Consider that the sentences are separated byConsider that the sentences are separated by
"".." and the words – by non-letter symbols." and the words – by non-letter symbols.
We are living in a yellow submarine. We don't haveWe are living in a yellow submarine. We don't have
anything else. Inside the submarine is very tight.anything else. Inside the submarine is very tight.
So we are drinking all the day. We will move outSo we are drinking all the day. We will move out
of it in 5 days.of it in 5 days.
We are living in a yellow submarine.We are living in a yellow submarine.
We will move out of it in 5 days.We will move out of it in 5 days.
Exercises (6)Exercises (6)
9.9. We are given a string containing a list of forbiddenWe are given a string containing a list of forbidden
words and a text containing some of these words.words and a text containing some of these words.
Write a program that replaces the forbidden wordsWrite a program that replaces the forbidden words
with asterisks. Example:with asterisks. Example:
Words: "PHP, CLR, Microsoft"Words: "PHP, CLR, Microsoft"
The expected result:The expected result:
Microsoft announced its next generation PHPMicrosoft announced its next generation PHP
compiler today. It is based on .NET Framework 4.0compiler today. It is based on .NET Framework 4.0
and is implemented as a dynamic language in CLR.and is implemented as a dynamic language in CLR.
********* announced its next generation ************ announced its next generation ***
compiler today. It is based on .NET Framework 4.0compiler today. It is based on .NET Framework 4.0
and is implemented as a dynamic language in ***.and is implemented as a dynamic language in ***.
Exercises (7)Exercises (7)
10.10. Write a program that converts a string to aWrite a program that converts a string to a
sequence of C# Unicode character literals. Usesequence of C# Unicode character literals. Use
format strings. Sample input:format strings. Sample input:
Expected output:Expected output:
11.11. Write a program that reads a number and prints itWrite a program that reads a number and prints it
as a decimal number, hexadecimal number,as a decimal number, hexadecimal number,
percentage and in scientific notation. Format thepercentage and in scientific notation. Format the
output aligned right in 15 symbols.output aligned right in 15 symbols.
Hi!Hi!
u0048u0069u0021u0048u0069u0021
Exercises (8)Exercises (8)
12.12. Write a program that parses an URL address givenWrite a program that parses an URL address given
in the format:in the format:
and extracts from it theand extracts from it the [protocol][protocol],, [server][server]
andand [resource][resource] elements. For example from theelements. For example from the
URLURL http://www.devbg.org/forum/index.phphttp://www.devbg.org/forum/index.php
the following information should be extracted:the following information should be extracted:
[protocol] = "http"[protocol] = "http"
[server] = "www.devbg.org"[server] = "www.devbg.org"
[resource] = "/forum/index.php"[resource] = "/forum/index.php"
[protocol]://[server]/[resource][protocol]://[server]/[resource]
Exercises (9)Exercises (9)
13.13. Write a program that reverses the words in givenWrite a program that reverses the words in given
sentence.sentence.
Example: "C# is not C++, not PHP and not Delphi!"Example: "C# is not C++, not PHP and not Delphi!"
 "Delphi not and PHP, not C++ not is C#!"."Delphi not and PHP, not C++ not is C#!".
14.14. A dictionary is stored as a sequence of text linesA dictionary is stored as a sequence of text lines
containing words and their explanations. Write acontaining words and their explanations. Write a
program that enters a word and translates it byprogram that enters a word and translates it by
using the dictionary. Sample dictionary:using the dictionary. Sample dictionary:
.NET – platform for applications from Microsoft.NET – platform for applications from Microsoft
CLR – managed execution environment for .NETCLR – managed execution environment for .NET
namespace – hierarchical organization of classesnamespace – hierarchical organization of classes
Exercises (10)Exercises (10)
15.15. Write a program that replaces in a HTMLWrite a program that replaces in a HTML
document given as string all the tagsdocument given as string all the tags <a<a
hrefhref="…">…</a>="…">…</a> with corresponding tagswith corresponding tags
[URL=…]…/URL][URL=…]…/URL]. Sample HTML fragment:. Sample HTML fragment:
<p>Please visit <a href="http://academy.telerik.<p>Please visit <a href="http://academy.telerik.
com">our site</a> to choose a training course. Alsocom">our site</a> to choose a training course. Also
visit <a href="www.devbg.org">our forum</a> tovisit <a href="www.devbg.org">our forum</a> to
discuss the courses.</p>discuss the courses.</p>
<p>Please visit [URL=http://academy.telerik.<p>Please visit [URL=http://academy.telerik.
com]our site[/URL] to choose a training course.com]our site[/URL] to choose a training course.
Also visit [URL=www.devbg.org]our forum[/URL] toAlso visit [URL=www.devbg.org]our forum[/URL] to
discuss the courses.</p>discuss the courses.</p>
Exercises (11)Exercises (11)
16.16. Write a program that reads two dates in theWrite a program that reads two dates in the
format:format: day.month.yearday.month.year and calculates theand calculates the
number of days between them. Example:number of days between them. Example:
17.17. Write a program that reads a date and time givenWrite a program that reads a date and time given
in the format:in the format: day.month.yearday.month.year
hour:minute:secondhour:minute:second and prints the date andand prints the date and
time after 6 hours and 30 minutes (in the sametime after 6 hours and 30 minutes (in the same
format).format).
Enter the first date: 27.02.2006Enter the first date: 27.02.2006
Enter the second date: 3.03.2004Enter the second date: 3.03.2004
Distance: 4 daysDistance: 4 days
Exercises (12)Exercises (12)
18.18. Write a program for extracting all the emailWrite a program for extracting all the email
addresses from given text. All substrings thataddresses from given text. All substrings that
match the formatmatch the format <identifier>@<host>…<identifier>@<host>…
<domain><domain> should be recognized as emails.should be recognized as emails.
19.19. Write a program that extracts from a given text allWrite a program that extracts from a given text all
the dates that match the formatthe dates that match the format DD.MM.YYYYDD.MM.YYYY..
Display them in the standard date format forDisplay them in the standard date format for
Canada.Canada.
20.20. Write a program that extracts from a given text allWrite a program that extracts from a given text all
palindromes, e.g. "palindromes, e.g. "ABBAABBA", "", "lamallamal", "", "exeexe".".
Exercises (13)Exercises (13)
21.21. Write a program that reads a string from theWrite a program that reads a string from the
console and prints all different letters in the stringconsole and prints all different letters in the string
along with information how many times eachalong with information how many times each
letter is found.letter is found.
22.22. Write a program that reads a string from theWrite a program that reads a string from the
console and lists all different words in the stringconsole and lists all different words in the string
along with information how many times each wordalong with information how many times each word
is found.is found.
23.23. Write a program that reads a string from theWrite a program that reads a string from the
console and replaces all series of consecutiveconsole and replaces all series of consecutive
identical letters with a single one. Example:identical letters with a single one. Example:
""aaaaabbbbbcdddeeeedssaaaaaaabbbbbcdddeeeedssaa""  ""abcdedsaabcdedsa".".
Exercises (14)Exercises (14)
24.24. Write a program that reads a list of words,Write a program that reads a list of words,
separated by spaces and prints the list in anseparated by spaces and prints the list in an
alphabetical order.alphabetical order.
25.25. Write a program that extracts from given HTMLWrite a program that extracts from given HTML
file its title (if available), and its body text withoutfile its title (if available), and its body text without
the HTML tags. Example:the HTML tags. Example:
<html><html>
<head><title>News</title></head><head><title>News</title></head>
<body><p><a href="http://academy.telerik.com">Telerik<body><p><a href="http://academy.telerik.com">Telerik
Academy</a>aims to provide free real-world practicalAcademy</a>aims to provide free real-world practical
training for young people who want to turn intotraining for young people who want to turn into
skillful .NET software engineers.</p></body>skillful .NET software engineers.</p></body>
</html></html>

More Related Content

PPT
String Handling
PDF
String handling(string class)
PDF
Arrays string handling java packages
PPS
String and string buffer
PPT
String handling session 5
PPTX
Java Strings
PPTX
Chapter 14 strings
PPTX
String, string builder, string buffer
String Handling
String handling(string class)
Arrays string handling java packages
String and string buffer
String handling session 5
Java Strings
Chapter 14 strings
String, string builder, string buffer

What's hot (20)

PPTX
Java string , string buffer and wrapper class
PPT
String classes and its methods.20
PPTX
Introduction to Java Strings, By Kavita Ganesan
PPTX
Strings in Java
PPTX
String Builder & String Buffer (Java Programming)
PPTX
String in python lecture (3)
PDF
Python strings
PPTX
Python strings presentation
PDF
awesome groovy
ODP
GPars (Groovy Parallel Systems)
PPTX
concurrency gpars
PDF
Manipulating strings
PPTX
String in python use of split method
PDF
String.ppt
PDF
LectureNotes-04-DSA
PDF
groovy rules
PDF
functional groovy
PPTX
String java
PDF
Strings part2
KEY
Erlang/OTP for Rubyists
Java string , string buffer and wrapper class
String classes and its methods.20
Introduction to Java Strings, By Kavita Ganesan
Strings in Java
String Builder & String Buffer (Java Programming)
String in python lecture (3)
Python strings
Python strings presentation
awesome groovy
GPars (Groovy Parallel Systems)
concurrency gpars
Manipulating strings
String in python use of split method
String.ppt
LectureNotes-04-DSA
groovy rules
functional groovy
String java
Strings part2
Erlang/OTP for Rubyists
Ad

Viewers also liked (7)

PPSX
String and string manipulation x
PPT
More Pointers and Arrays
PPTX
PPTX
C programming - Pointers
PPTX
C programming - String
PPT
PDF
Pointers
String and string manipulation x
More Pointers and Arrays
C programming - Pointers
C programming - String
Pointers
Ad

Similar to 13 Strings and text processing (20)

PPTX
16 strings-and-text-processing-120712074956-phpapp02
PPTX
13 Strings and Text Processing
PDF
Module 6 - String Manipulation.pdf
PPTX
13string in c#
PPTX
PPT
String and string manipulation
PPTX
Strings in c#
PPT
Strings Arrays
PDF
05 c++-strings
PPT
Csphtp1 15
PPTX
Computer programming 2 Lesson 12
PPTX
L13 string handling(string class)
PPTX
String in .net
PPTX
Core C# Programming Constructs, Part 1
PDF
String handling(string class)
PPTX
Java string handling
PDF
OOPs difference faqs- 4
PPT
Strings
PPTX
Cs1123 9 strings
PPTX
The string class
16 strings-and-text-processing-120712074956-phpapp02
13 Strings and Text Processing
Module 6 - String Manipulation.pdf
13string in c#
String and string manipulation
Strings in c#
Strings Arrays
05 c++-strings
Csphtp1 15
Computer programming 2 Lesson 12
L13 string handling(string class)
String in .net
Core C# Programming Constructs, Part 1
String handling(string class)
Java string handling
OOPs difference faqs- 4
Strings
Cs1123 9 strings
The string class

More from maznabili (20)

PPT
22 Methodology of problem solving
PPT
21 High-quality programming code construction part-ii
PPT
21 high-quality programming code construction part-i
PPT
20 Object-oriented programming principles
PPT
19 Algorithms and complexity
PPT
18 Hash tables and sets
PPT
17 Trees and graphs
PPT
16 Linear data structures
PPT
15 Text files
PPT
14 Defining classes
PPT
12 Exceptions handling
PPT
11 Using classes and objects
PPT
10 Recursion
PPT
09 Methods
PPT
08 Numeral systems
PPT
07 Arrays
PPT
06 Loops
PPT
05 Conditional statements
PPT
04 Console input output-
PPT
03 Operators and expressions
22 Methodology of problem solving
21 High-quality programming code construction part-ii
21 high-quality programming code construction part-i
20 Object-oriented programming principles
19 Algorithms and complexity
18 Hash tables and sets
17 Trees and graphs
16 Linear data structures
15 Text files
14 Defining classes
12 Exceptions handling
11 Using classes and objects
10 Recursion
09 Methods
08 Numeral systems
07 Arrays
06 Loops
05 Conditional statements
04 Console input output-
03 Operators and expressions

Recently uploaded (20)

PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Empathic Computing: Creating Shared Understanding
PDF
Machine learning based COVID-19 study performance prediction
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Spectroscopy.pptx food analysis technology
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPT
Teaching material agriculture food technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
cuic standard and advanced reporting.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
MIND Revenue Release Quarter 2 2025 Press Release
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Mobile App Security Testing_ A Comprehensive Guide.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Electronic commerce courselecture one. Pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Empathic Computing: Creating Shared Understanding
Machine learning based COVID-19 study performance prediction
Diabetes mellitus diagnosis method based random forest with bat algorithm
Spectroscopy.pptx food analysis technology
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
“AI and Expert System Decision Support & Business Intelligence Systems”
Advanced methodologies resolving dimensionality complications for autism neur...
Teaching material agriculture food technology
Review of recent advances in non-invasive hemoglobin estimation
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Programs and apps: productivity, graphics, security and other tools
cuic standard and advanced reporting.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy

13 Strings and text processing

  • 1. Strings andTextStrings andText ProcessingProcessing Processing and ManipulatingText InformationProcessing and ManipulatingText Information Svetlin NakovSvetlin Nakov Telerik CorporationTelerik Corporation www.telerik.comwww.telerik.com
  • 2. Table of ContentsTable of Contents 1.1. What is String?What is String? 2.2. Creating and Using StringsCreating and Using Strings  Declaring, Creating, Reading and PrintingDeclaring, Creating, Reading and Printing 1.1. Manipulating StringsManipulating Strings  Comparing, Concatenating, Searching,Comparing, Concatenating, Searching, Extracting Substrings, SplittingExtracting Substrings, Splitting 1.1. Other String OperationsOther String Operations  Replacing Substrings, Deleting Substrings,Replacing Substrings, Deleting Substrings, Changing Character Casing, TrimmingChanging Character Casing, Trimming
  • 3. Table of Contents (2)Table of Contents (2) 5.5. Building and Modifying StringsBuilding and Modifying Strings  UsingUsing StringBuilderStringBuilder ClassClass 5.5. Formatting StringsFormatting Strings
  • 4. What Is String?What Is String?
  • 5. What Is String?What Is String?  Strings are sequences of charactersStrings are sequences of characters  Each character is a Unicode symbolEach character is a Unicode symbol  Represented by theRepresented by the stringstring data type in C#data type in C# ((System.StringSystem.String))  Example:Example: string s = "Hello, C#";string s = "Hello, C#"; HH ee ll ll oo ,, CC ##ss
  • 6. TheThe System.StringSystem.String ClassClass  Strings are represented byStrings are represented by System.StringSystem.String objects in .NET Frameworkobjects in .NET Framework String objects contain an immutable (read-only)String objects contain an immutable (read-only) sequence of characterssequence of characters Strings use Unicode in to support multipleStrings use Unicode in to support multiple languages and alphabetslanguages and alphabets  Strings are stored in the dynamic memoryStrings are stored in the dynamic memory ((managed heapmanaged heap))  System.StringSystem.String is reference typeis reference type
  • 7. TheThe System.StringSystem.String Class (2)Class (2)  String objects are like arrays of charactersString objects are like arrays of characters ((char[]char[])) Have fixed length (Have fixed length (String.LengthString.Length)) Elements can be accessed directly by indexElements can be accessed directly by index  The index is in the range [The index is in the range [00......Length-1Length-1]] string s = "Hello!";string s = "Hello!"; int len = s.Length; // len = 6int len = s.Length; // len = 6 char ch = s[1]; // ch = 'e'char ch = s[1]; // ch = 'e' 00 11 22 33 44 55 HH ee ll ll oo !! index =index = s[index] =s[index] =
  • 8. Strings – First ExampleStrings – First Example static void Main()static void Main() {{ string s =string s = "Stand up, stand up, Balkan Superman.";"Stand up, stand up, Balkan Superman."; Console.WriteLine("s = "{0}"", s);Console.WriteLine("s = "{0}"", s); Console.WriteLine("s.Length = {0}", s.Length);Console.WriteLine("s.Length = {0}", s.Length); for (int i = 0; i < s.Length; i++)for (int i = 0; i < s.Length; i++) {{ Console.WriteLine("s[{0}] = {1}", i, s[i]);Console.WriteLine("s[{0}] = {1}", i, s[i]); }} }}
  • 9. Strings – First ExampleStrings – First Example Live DemoLive Demo
  • 10. Creating and Using StringsCreating and Using Strings Declaring, Creating, Reading and PrintingDeclaring, Creating, Reading and Printing
  • 11. Declaring StringsDeclaring Strings  There are two ways of declaring stringThere are two ways of declaring string variables:variables: UsingUsing thethe C#C# keywordkeyword stringstring Using the .NET's fully qualified class nameUsing the .NET's fully qualified class name System.StringSystem.String The above three declarations are equivalentThe above three declarations are equivalent string str1;string str1; System.String str2;System.String str2; String str3;String str3;
  • 12. Creating StringsCreating Strings  Before initializing a string variable hasBefore initializing a string variable has nullnull valuevalue  Strings can be initialized by:Strings can be initialized by: Assigning a string literal to the string variableAssigning a string literal to the string variable Assigning the value of another string variableAssigning the value of another string variable Assigning the result of operation of type stringAssigning the result of operation of type string
  • 13. Creating Strings (2)Creating Strings (2)  Not initialized variables has value ofNot initialized variables has value of nullnull  Assigning a string literalAssigning a string literal  Assigning from another string variableAssigning from another string variable  Assigning from the result of string operationAssigning from the result of string operation string s; // s is equal to nullstring s; // s is equal to null string s = "I am a string literal!";string s = "I am a string literal!"; string s2 = s;string s2 = s; string s = 42.ToString();string s = 42.ToString();
  • 14. Reading and Printing StringsReading and Printing Strings  Reading strings from the consoleReading strings from the console Use the methodUse the method Console.Console.ReadLine()ReadLine() string s = Console.ReadLine();string s = Console.ReadLine(); Console.Write("Please enter your name: ");Console.Write("Please enter your name: "); string name = Console.ReadLine();string name = Console.ReadLine(); Console.Write("Hello, {0}! ", name);Console.Write("Hello, {0}! ", name); Console.WriteLine("Welcome to our party!");Console.WriteLine("Welcome to our party!");  Printing strings to the consolePrinting strings to the console  Use the methodsUse the methods Write()Write() andand WriteLine()WriteLine()
  • 15. Reading and Printing StringsReading and Printing Strings Live DemoLive Demo
  • 16. Comparing, Concatenating, Searching,Comparing, Concatenating, Searching, Extracting Substrings, SplittingExtracting Substrings, Splitting Manipulating StringsManipulating Strings
  • 17. Comparing StringsComparing Strings  A number of ways exist to compare twoA number of ways exist to compare two strings:strings: Dictionary-based string comparisonDictionary-based string comparison  Case-insensitiveCase-insensitive  Case-sensitiveCase-sensitive int result = string.Compare(str1, str2, true);int result = string.Compare(str1, str2, true); // result == 0 if str1 equals str2// result == 0 if str1 equals str2 // result < 0 if str1 if before str2// result < 0 if str1 if before str2 // result > 0 if str1 if after str2// result > 0 if str1 if after str2 string.Compare(str1, str2, false);string.Compare(str1, str2, false);
  • 18. Comparing Strings (2)Comparing Strings (2)  Equality checking by operatorEquality checking by operator ==== Performs case-sensitive comparePerforms case-sensitive compare  Using the case-sensitiveUsing the case-sensitive Equals()Equals() methodmethod The same effect like the operatorThe same effect like the operator ==== if (str1 == str2)if (str1 == str2) {{ …… }} if (str1.Equals(str2))if (str1.Equals(str2)) {{ …… }}
  • 19. Comparing Strings – ExampleComparing Strings – Example  Finding the first string in a lexicographical orderFinding the first string in a lexicographical order from a given list of strings:from a given list of strings: string[] towns = {"Sofia", "Varna", "Plovdiv",string[] towns = {"Sofia", "Varna", "Plovdiv", "Pleven", "Bourgas", "Rousse", "Yambol"};"Pleven", "Bourgas", "Rousse", "Yambol"}; string firstTown = towns[0];string firstTown = towns[0]; for (int i=1; i<towns.Length; i++)for (int i=1; i<towns.Length; i++) {{ string currentTown = towns[i];string currentTown = towns[i]; if (String.Compare(currentTown, firstTown) < 0)if (String.Compare(currentTown, firstTown) < 0) {{ firstTown = currentTown;firstTown = currentTown; }} }} Console.WriteLine("First town: {0}", firstTown);Console.WriteLine("First town: {0}", firstTown);
  • 20. Live DemoLive Demo Comparing StringsComparing Strings
  • 21. Concatenating StringsConcatenating Strings  There are two ways to combine strings:There are two ways to combine strings:  Using theUsing the Concat()Concat() methodmethod  Using theUsing the ++ or theor the +=+= operatorsoperators  Any object can be appended to stringAny object can be appended to string string str = String.Concat(str1, str2);string str = String.Concat(str1, str2); string str = str1 + str2 + str3;string str = str1 + str2 + str3; string str += str1;string str += str1; string name = "Peter";string name = "Peter"; int age = 22;int age = 22; string s = name + " " + age; //string s = name + " " + age; //  "Peter 22""Peter 22"
  • 22. Concatenating Strings –Concatenating Strings – ExampleExample string firstName = "Svetlin";string firstName = "Svetlin"; string lastName = "Nakov";string lastName = "Nakov"; string fullName = firstName + " " + lastName;string fullName = firstName + " " + lastName; Console.WriteLine(fullName);Console.WriteLine(fullName); // Svetlin Nakov// Svetlin Nakov int age = 25;int age = 25; string nameAndAge =string nameAndAge = "Name: " + fullName +"Name: " + fullName + "nAge: " + age;"nAge: " + age; Console.WriteLine(nameAndAge);Console.WriteLine(nameAndAge); // Name: Svetlin Nakov// Name: Svetlin Nakov // Age: 25// Age: 25
  • 24. Searching in StringsSearching in Strings  Finding a character or substring within givenFinding a character or substring within given stringstring  First occurrenceFirst occurrence  First occurrence starting at given positionFirst occurrence starting at given position  Last occurrenceLast occurrence IndexOf(string str)IndexOf(string str) IndexOf(string str, int startIndex)IndexOf(string str, int startIndex) LastIndexOf(string)LastIndexOf(string)
  • 25. Searching in Strings – ExampleSearching in Strings – Example string str = "C# Programming Course";string str = "C# Programming Course"; int index = str.IndexOf("C#"); // index = 0int index = str.IndexOf("C#"); // index = 0 index = str.IndexOf("Course"); // index = 15index = str.IndexOf("Course"); // index = 15 index = str.IndexOf("COURSE"); // index = -1index = str.IndexOf("COURSE"); // index = -1 // IndexOf is case-sensetive. -1 means not found// IndexOf is case-sensetive. -1 means not found index = str.IndexOf("ram"); // index = 7index = str.IndexOf("ram"); // index = 7 index = str.IndexOf("r"); // index = 4index = str.IndexOf("r"); // index = 4 index = str.IndexOf("r", 5); // index = 7index = str.IndexOf("r", 5); // index = 7 index = str.IndexOf("r", 8); // index = 18index = str.IndexOf("r", 8); // index = 18 00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 …… CC ## PP rr oo gg rr aa mm mm ii nn gg …… index =index = s[index] =s[index] =
  • 27. Extracting SubstringsExtracting Substrings  Extracting substringsExtracting substrings  str.Substring(int startIndex, int length)str.Substring(int startIndex, int length)  str.Substring(int startIndex)str.Substring(int startIndex) string filename = @"C:PicsRila2009.jpg";string filename = @"C:PicsRila2009.jpg"; string name = filename.Substring(8, 8);string name = filename.Substring(8, 8); // name is Rila2009// name is Rila2009 string filename = @"C:PicsSummer2009.jpg";string filename = @"C:PicsSummer2009.jpg"; string nameAndExtension = filename.Substring(8);string nameAndExtension = filename.Substring(8); // nameAndExtension is Summer2009.jpg// nameAndExtension is Summer2009.jpg 00 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717 1818 1919 CC :: PP ii cc ss RR ii ll aa 22 00 00 55 .. jj pp gg
  • 28. Live DemoLive Demo Extracting SubstringsExtracting Substrings
  • 29. Splitting StringsSplitting Strings  To split a string by given separator(s) use theTo split a string by given separator(s) use the following method:following method:  Example:Example: string[] Split(params char[])string[] Split(params char[]) string listOfBeers =string listOfBeers = "Amstel, Zagorka, Tuborg, Becks.";"Amstel, Zagorka, Tuborg, Becks."; string[] beers =string[] beers = listOfBeers.Split(' ', ',', '.');listOfBeers.Split(' ', ',', '.'); Console.WriteLine("Available beers are:");Console.WriteLine("Available beers are:"); foreach (string beer in beers)foreach (string beer in beers) {{ Console.WriteLine(beer);Console.WriteLine(beer); }}
  • 30. Live DemoLive Demo Splitting StringsSplitting Strings
  • 31. Other String OperationsOther String Operations Replacing Substrings, Deleting Substrings,Replacing Substrings, Deleting Substrings, Changing Character Casing, TrimmingChanging Character Casing, Trimming
  • 32. Replacing and Deleting SubstringsReplacing and Deleting Substrings  Replace(string,Replace(string, string)string) – replaces all– replaces all occurrences of given string with anotheroccurrences of given string with another  The result is new string (strings are immutable)The result is new string (strings are immutable)  ReRemovemove((indexindex,, lengthlength)) – deletes part of a string– deletes part of a string and produces new string as resultand produces new string as result string cocktail = "Vodka + Martini + Cherry";string cocktail = "Vodka + Martini + Cherry"; string replaced = cocktail.Replace("+", "and");string replaced = cocktail.Replace("+", "and"); // Vodka and Martini and Cherry// Vodka and Martini and Cherry string price = "$ 1234567";string price = "$ 1234567"; string lowPrice = price.Remove(2, 3);string lowPrice = price.Remove(2, 3); // $ 4567// $ 4567
  • 33. Changing Character CasingChanging Character Casing  Using methodUsing method ToLower()ToLower()  Using methodUsing method ToUpper()ToUpper() string alpha = "aBcDeFg";string alpha = "aBcDeFg"; string lowerAlpha = alpha.ToLower(); // abcdefgstring lowerAlpha = alpha.ToLower(); // abcdefg Console.WriteLine(lowerAlpha);Console.WriteLine(lowerAlpha); string alpha = "aBcDeFg";string alpha = "aBcDeFg"; string upperAlpha = alpha.ToUpper(); // ABCDEFGstring upperAlpha = alpha.ToUpper(); // ABCDEFG Console.WriteLine(upperAlpha);Console.WriteLine(upperAlpha);
  • 34. Trimming White SpaceTrimming White Space  Using methodUsing method Trim()Trim()  Using methodUsing method Trim(charsTrim(chars))  UsingUsing TrimTrimStartStart()() andand TrimTrimEndEnd()() string s = " example of white space ";string s = " example of white space "; string clean = s.Trim();string clean = s.Trim(); Console.WriteLine(clean);Console.WriteLine(clean); string s = " tnHello!!! n";string s = " tnHello!!! n"; string clean = s.Trim(' ', ',' ,'!', 'n','t');string clean = s.Trim(' ', ',' ,'!', 'n','t'); Console.WriteLine(clean); // HelloConsole.WriteLine(clean); // Hello string s = " C# ";string s = " C# "; string clean = s.TrimStart(); // clean = "C# "string clean = s.TrimStart(); // clean = "C# "
  • 35. Other String OperationsOther String Operations Live DemoLive Demo
  • 36. Building and Modifying StringsBuilding and Modifying Strings UsingUsing StringBuilderStringBuilder CClasslass
  • 37. Constructing StringsConstructing Strings  Strings are immutableStrings are immutable CConcat()oncat(),, RReplace()eplace(),, TTrim()rim(), ..., ... return newreturn new string, do not modify the old onestring, do not modify the old one  Do not use "Do not use "++" for strings in a loop!" for strings in a loop! It runs very, very inefficiently!It runs very, very inefficiently! public static string DupChar(char ch, int count)public static string DupChar(char ch, int count) {{ string result = "";string result = ""; for (int i=0; i<count; i++)for (int i=0; i<count; i++) result += ch;result += ch; return result;return result; }} Very badVery bad practice. Avoidpractice. Avoid this!this!
  • 38. Slow Building Strings with +Slow Building Strings with + Live DemoLive Demo
  • 39. Changing the Contents of a StringChanging the Contents of a String –– StringBuilderStringBuilder  Use theUse the System.Text.StringBuilderSystem.Text.StringBuilder class forclass for modifiable strings of characters:modifiable strings of characters:  UseUse StringBuilderStringBuilder if you need to keep addingif you need to keep adding characters to a stringcharacters to a string public static string ReverseString(string s)public static string ReverseString(string s) {{ StringBuilder sb = new StringBuilder();StringBuilder sb = new StringBuilder(); for (int i = s.Length-1; i >= 0; i--)for (int i = s.Length-1; i >= 0; i--) sb.Append(s[i]);sb.Append(s[i]); return sb.ToString();return sb.ToString(); }}
  • 40. TheThe StringBuildeStringBuilder Classr Class  StringBuilderStringBuilder keeps a buffer memory,keeps a buffer memory, allocated in advanceallocated in advance Most operations use the buffer memory andMost operations use the buffer memory and do not allocate new objectsdo not allocate new objects HH ee ll ll oo ,, CC ## !!StringBuilderStringBuilder:: Length=9Length=9 Capacity=15Capacity=15 CapacityCapacity used bufferused buffer (Length)(Length) unusedunused bufferbuffer
  • 41. TheThe StringBuildeStringBuilder Class (2)r Class (2)  StringBuilder(int capacity)StringBuilder(int capacity) constructorconstructor allocates in advance buffer memory of a givenallocates in advance buffer memory of a given sizesize  By default 16 characters are allocatedBy default 16 characters are allocated  CapacityCapacity holds the currently allocated space (inholds the currently allocated space (in characters)characters)  this[int index]this[int index] (indexer in C#) gives access(indexer in C#) gives access to the char value at given positionto the char value at given position  LengthLength holds the length of the string in theholds the length of the string in the bufferbuffer
  • 42. TheThe StringBuildeStringBuilder Class (3)r Class (3)  Append(…)Append(…) appends string or another object after theappends string or another object after the last character in the bufferlast character in the buffer  RemoveRemove(int start(int startIndexIndex,, intint lengthlength)) removesremoves the characters in given rangethe characters in given range  IInsert(intnsert(int indexindex,, sstring str)tring str) inserts giveninserts given string (or object) at given positionstring (or object) at given position  Replace(string oldStr,Replace(string oldStr, string newStr)string newStr) replaces all occurrences of a substring with new stringreplaces all occurrences of a substring with new string  TToString()oString() converts theconverts the StringBuilderStringBuilder toto StringString
  • 43. StringBuilderStringBuilder – Example– Example  Extracting all capital letters from a stringExtracting all capital letters from a string public static string ExtractCapitals(string s)public static string ExtractCapitals(string s) {{ StringBuilder result = new StringBuilder();StringBuilder result = new StringBuilder(); for (int i = 0; i<s.Length; i++)for (int i = 0; i<s.Length; i++) {{ if (Char.IsUpper(s[i]))if (Char.IsUpper(s[i])) {{ result.Append(s[i]);result.Append(s[i]); }} }} return result.ToString();return result.ToString(); }}
  • 44. How theHow the ++ Operator Does StringOperator Does String Concatenations?Concatenations?  Consider following string concatenation:Consider following string concatenation:  It is equivalent to this code:It is equivalent to this code:  Actually several new objects are created andActually several new objects are created and leaved to the garbage collectorleaved to the garbage collector  What happens when usingWhat happens when using ++ in a loop?in a loop? string result = str1 + str2;string result = str1 + str2; StringBuilder sb = new StringBuilder();StringBuilder sb = new StringBuilder(); sb.Append(str1);sb.Append(str1); sb.Append(str2);sb.Append(str2); string result = sb.ToString();string result = sb.ToString();
  • 46. Formatting StringsFormatting Strings UsingUsing ToString()ToString() andand String.Format()String.Format()
  • 47. MethodMethod ToString()ToString()  All classes have public virtual methodAll classes have public virtual method ToString()ToString() Returns a human-readable, culture-sensitiveReturns a human-readable, culture-sensitive string representing the objectstring representing the object Most .NET Framework types have ownMost .NET Framework types have own implementation ofimplementation of ToString()ToString()  intint,, floatfloat,, boolbool,, DateTimeDateTime int number = 5;int number = 5; string s = "The number is " + number.ToString();string s = "The number is " + number.ToString(); Console.WriteLine(s); // The number is 5Console.WriteLine(s); // The number is 5
  • 48. MethodMethod ToString(formatToString(format))  We can apply specific formatting whenWe can apply specific formatting when converting objects to stringconverting objects to string  ToString(foToString(forrmatString)matString) methodmethod int number = 42;int number = 42; string s = number.ToString("D5"); // 00042string s = number.ToString("D5"); // 00042 s = number.ToString("X"); // 2As = number.ToString("X"); // 2A // Consider the default culture is Bulgarian// Consider the default culture is Bulgarian s = number.ToString("C"); // 42,00 лвs = number.ToString("C"); // 42,00 лв double d = 0.375;double d = 0.375; s = d.ToString("P2"); // 37,50 %s = d.ToString("P2"); // 37,50 %
  • 49. Formatting StringsFormatting Strings  The formatting strings are different for theThe formatting strings are different for the different typesdifferent types  Some formatting strings for numbers:Some formatting strings for numbers:  DD – number (for integer types)– number (for integer types)  CC – currency (according to current culture)– currency (according to current culture)  EE – number in exponential notation– number in exponential notation  PP – percentage– percentage  XX – hexadecimal number– hexadecimal number  FF – fixed point (for real numbers)– fixed point (for real numbers)
  • 50. MethodMethod String.Format()String.Format()  AppliesApplies templatestemplates for formatting stringsfor formatting strings Placeholders are used for dynamic textPlaceholders are used for dynamic text LikeLike Console.WriteLine(…)Console.WriteLine(…) string template = "If I were {0}, I would {1}.";string template = "If I were {0}, I would {1}."; string sentence1 = String.Format(string sentence1 = String.Format( template, "developer", "know C#");template, "developer", "know C#"); Console.WriteLine(sentence1);Console.WriteLine(sentence1); // If I were developer, I would know C#.// If I were developer, I would know C#. string sentence2 = String.Format(string sentence2 = String.Format( template, "elephant", "weigh 4500 kg");template, "elephant", "weigh 4500 kg"); Console.WriteLine(sentence2);Console.WriteLine(sentence2); // If I were elephant, I would weigh 4500 kg.// If I were elephant, I would weigh 4500 kg.
  • 51. Composite FormattingComposite Formatting  The placeholders in the composite formattingThe placeholders in the composite formatting strings are specified as follows:strings are specified as follows:  Examples:Examples: {index[,alignment][:formatString]}{index[,alignment][:formatString]} double d = 0.375;double d = 0.375; s = String.Format("{0,10:F5}", d);s = String.Format("{0,10:F5}", d); // s = " 0,37500"// s = " 0,37500" int number = 42;int number = 42; Console.WriteLine("Dec {0:D} = Hex {1:X}",Console.WriteLine("Dec {0:D} = Hex {1:X}", number, number);number, number); // Dec 42 = Hex 2A// Dec 42 = Hex 2A
  • 52. Formatting DatesFormatting Dates  Dates have their own formatting stringsDates have their own formatting strings dd,, dddd –– day (with/without leading zero)day (with/without leading zero) MM,, MMMM –– monthmonth yyyy,, yyyyyyyy –– year (2 or 4 digits)year (2 or 4 digits) hh,, HHHH,, mm,, mmmm,, ss,, ssss –– hour, minute, secondhour, minute, second DateTime now = DateTime.Now;DateTime now = DateTime.Now; Console.WriteLine(Console.WriteLine( "Now is {0:d.MM.yyyy HH:mm:ss}", now);"Now is {0:d.MM.yyyy HH:mm:ss}", now); // Now is 31.11.2009 11:30:32// Now is 31.11.2009 11:30:32
  • 54. SummarySummary  Strings are immutable sequences of charactersStrings are immutable sequences of characters (instances of(instances of System.StringSystem.String))  Declared by the keywordDeclared by the keyword stringstring in C#in C#  Can be initialized by string literalsCan be initialized by string literals  Most important string processing members are:Most important string processing members are:  LengthLength,, this[]this[],, Compare(str1,Compare(str1, str2)str2),, IndexOf(str)IndexOf(str),, LastIndexOf(str)LastIndexOf(str),, Substring(startIndex,Substring(startIndex, length)length),, Replace(oldStr,Replace(oldStr, newStr)newStr),, Remove(startIndex,Remove(startIndex, length)length),, ToLower()ToLower(),, ToUpper()ToUpper(),, Trim()Trim()
  • 55. Summary (2)Summary (2)  Objects can be converted to strings and can beObjects can be converted to strings and can be formatted in different styles (usingformatted in different styles (using ToStringToString()() method)method)  Strings can be constructed by usingStrings can be constructed by using placeholders and formatting stringsplaceholders and formatting strings ((String.FormatString.Format(…)(…)))
  • 56. Strings and Text ProcessingStrings and Text Processing Questions?Questions? http://academy.telerik.com
  • 57. ExercisesExercises 1.1. Describe the strings in C#. What is typical for theDescribe the strings in C#. What is typical for the stringstring data type? Describe the most importantdata type? Describe the most important methods of themethods of the StringString class.class. 2.2. Write a program that reads a string, reverses it andWrite a program that reads a string, reverses it and prints it on the console. Example: "sample"prints it on the console. Example: "sample"  ""elpmaselpmas".". 3.3. Write a program to check if in a given expression theWrite a program to check if in a given expression the brackets are put correctly. Example of correctbrackets are put correctly. Example of correct expression:expression: ((a+b)/5-d)((a+b)/5-d). Example of incorrect. Example of incorrect expression:expression: )(a+b)))(a+b))..
  • 58. Exercises (2)Exercises (2) 4.4. Write a program that finds how many times aWrite a program that finds how many times a substring is contained in a given text (perform casesubstring is contained in a given text (perform case insensitive search).insensitive search). Example: The target substring is "Example: The target substring is "inin". The text". The text is as follows:is as follows: The result is: 9.The result is: 9. We are living in an yellow submarine. We don'tWe are living in an yellow submarine. We don't have anything else. Inside the submarine is veryhave anything else. Inside the submarine is very tight. So we are drinking all the day. We willtight. So we are drinking all the day. We will move out of it in 5 days.move out of it in 5 days.
  • 59. Exercises (3)Exercises (3) 5.5. You are given a text. Write a program that changesYou are given a text. Write a program that changes the text in all regions surrounded by the tagsthe text in all regions surrounded by the tags <upcase><upcase> andand </upcase></upcase> to uppercase. The tagsto uppercase. The tags cannot be nested. Example:cannot be nested. Example: The expected result:The expected result: We are living in a <upcase>yellowWe are living in a <upcase>yellow submarine</upcase>. We don't havesubmarine</upcase>. We don't have <upcase>anything</upcase> else.<upcase>anything</upcase> else. We are living in a YELLOW SUBMARINE. We don't haveWe are living in a YELLOW SUBMARINE. We don't have ANYTHING else.ANYTHING else.
  • 60. Exercises (4)Exercises (4) 6.6. Write a program that reads from the console a stringWrite a program that reads from the console a string of maximum 20 characters. If the length of the stringof maximum 20 characters. If the length of the string is less than 20, the rest of the characters should beis less than 20, the rest of the characters should be filled with '*'. Print the result string into the console.filled with '*'. Print the result string into the console. 7.7. Write a program that encodes and decodes a stringWrite a program that encodes and decodes a string using given encryption key (cipher). The key consistsusing given encryption key (cipher). The key consists of a sequence of characters. The encoding/decodingof a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or) operationis done by performing XOR (exclusive or) operation over the first letter of the string with the first of theover the first letter of the string with the first of the key, the second – with the second, etc. When thekey, the second – with the second, etc. When the last key character is reached, the next is the first.last key character is reached, the next is the first.
  • 61. Exercises (5)Exercises (5) 8.8. Write a program that extracts from a given text allWrite a program that extracts from a given text all sentences containing given word.sentences containing given word. Example: The word is "Example: The word is "inin". The text is:". The text is: The expected result is:The expected result is: Consider that the sentences are separated byConsider that the sentences are separated by "".." and the words – by non-letter symbols." and the words – by non-letter symbols. We are living in a yellow submarine. We don't haveWe are living in a yellow submarine. We don't have anything else. Inside the submarine is very tight.anything else. Inside the submarine is very tight. So we are drinking all the day. We will move outSo we are drinking all the day. We will move out of it in 5 days.of it in 5 days. We are living in a yellow submarine.We are living in a yellow submarine. We will move out of it in 5 days.We will move out of it in 5 days.
  • 62. Exercises (6)Exercises (6) 9.9. We are given a string containing a list of forbiddenWe are given a string containing a list of forbidden words and a text containing some of these words.words and a text containing some of these words. Write a program that replaces the forbidden wordsWrite a program that replaces the forbidden words with asterisks. Example:with asterisks. Example: Words: "PHP, CLR, Microsoft"Words: "PHP, CLR, Microsoft" The expected result:The expected result: Microsoft announced its next generation PHPMicrosoft announced its next generation PHP compiler today. It is based on .NET Framework 4.0compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in CLR.and is implemented as a dynamic language in CLR. ********* announced its next generation ************ announced its next generation *** compiler today. It is based on .NET Framework 4.0compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language in ***.and is implemented as a dynamic language in ***.
  • 63. Exercises (7)Exercises (7) 10.10. Write a program that converts a string to aWrite a program that converts a string to a sequence of C# Unicode character literals. Usesequence of C# Unicode character literals. Use format strings. Sample input:format strings. Sample input: Expected output:Expected output: 11.11. Write a program that reads a number and prints itWrite a program that reads a number and prints it as a decimal number, hexadecimal number,as a decimal number, hexadecimal number, percentage and in scientific notation. Format thepercentage and in scientific notation. Format the output aligned right in 15 symbols.output aligned right in 15 symbols. Hi!Hi! u0048u0069u0021u0048u0069u0021
  • 64. Exercises (8)Exercises (8) 12.12. Write a program that parses an URL address givenWrite a program that parses an URL address given in the format:in the format: and extracts from it theand extracts from it the [protocol][protocol],, [server][server] andand [resource][resource] elements. For example from theelements. For example from the URLURL http://www.devbg.org/forum/index.phphttp://www.devbg.org/forum/index.php the following information should be extracted:the following information should be extracted: [protocol] = "http"[protocol] = "http" [server] = "www.devbg.org"[server] = "www.devbg.org" [resource] = "/forum/index.php"[resource] = "/forum/index.php" [protocol]://[server]/[resource][protocol]://[server]/[resource]
  • 65. Exercises (9)Exercises (9) 13.13. Write a program that reverses the words in givenWrite a program that reverses the words in given sentence.sentence. Example: "C# is not C++, not PHP and not Delphi!"Example: "C# is not C++, not PHP and not Delphi!"  "Delphi not and PHP, not C++ not is C#!"."Delphi not and PHP, not C++ not is C#!". 14.14. A dictionary is stored as a sequence of text linesA dictionary is stored as a sequence of text lines containing words and their explanations. Write acontaining words and their explanations. Write a program that enters a word and translates it byprogram that enters a word and translates it by using the dictionary. Sample dictionary:using the dictionary. Sample dictionary: .NET – platform for applications from Microsoft.NET – platform for applications from Microsoft CLR – managed execution environment for .NETCLR – managed execution environment for .NET namespace – hierarchical organization of classesnamespace – hierarchical organization of classes
  • 66. Exercises (10)Exercises (10) 15.15. Write a program that replaces in a HTMLWrite a program that replaces in a HTML document given as string all the tagsdocument given as string all the tags <a<a hrefhref="…">…</a>="…">…</a> with corresponding tagswith corresponding tags [URL=…]…/URL][URL=…]…/URL]. Sample HTML fragment:. Sample HTML fragment: <p>Please visit <a href="http://academy.telerik.<p>Please visit <a href="http://academy.telerik. com">our site</a> to choose a training course. Alsocom">our site</a> to choose a training course. Also visit <a href="www.devbg.org">our forum</a> tovisit <a href="www.devbg.org">our forum</a> to discuss the courses.</p>discuss the courses.</p> <p>Please visit [URL=http://academy.telerik.<p>Please visit [URL=http://academy.telerik. com]our site[/URL] to choose a training course.com]our site[/URL] to choose a training course. Also visit [URL=www.devbg.org]our forum[/URL] toAlso visit [URL=www.devbg.org]our forum[/URL] to discuss the courses.</p>discuss the courses.</p>
  • 67. Exercises (11)Exercises (11) 16.16. Write a program that reads two dates in theWrite a program that reads two dates in the format:format: day.month.yearday.month.year and calculates theand calculates the number of days between them. Example:number of days between them. Example: 17.17. Write a program that reads a date and time givenWrite a program that reads a date and time given in the format:in the format: day.month.yearday.month.year hour:minute:secondhour:minute:second and prints the date andand prints the date and time after 6 hours and 30 minutes (in the sametime after 6 hours and 30 minutes (in the same format).format). Enter the first date: 27.02.2006Enter the first date: 27.02.2006 Enter the second date: 3.03.2004Enter the second date: 3.03.2004 Distance: 4 daysDistance: 4 days
  • 68. Exercises (12)Exercises (12) 18.18. Write a program for extracting all the emailWrite a program for extracting all the email addresses from given text. All substrings thataddresses from given text. All substrings that match the formatmatch the format <identifier>@<host>…<identifier>@<host>… <domain><domain> should be recognized as emails.should be recognized as emails. 19.19. Write a program that extracts from a given text allWrite a program that extracts from a given text all the dates that match the formatthe dates that match the format DD.MM.YYYYDD.MM.YYYY.. Display them in the standard date format forDisplay them in the standard date format for Canada.Canada. 20.20. Write a program that extracts from a given text allWrite a program that extracts from a given text all palindromes, e.g. "palindromes, e.g. "ABBAABBA", "", "lamallamal", "", "exeexe".".
  • 69. Exercises (13)Exercises (13) 21.21. Write a program that reads a string from theWrite a program that reads a string from the console and prints all different letters in the stringconsole and prints all different letters in the string along with information how many times eachalong with information how many times each letter is found.letter is found. 22.22. Write a program that reads a string from theWrite a program that reads a string from the console and lists all different words in the stringconsole and lists all different words in the string along with information how many times each wordalong with information how many times each word is found.is found. 23.23. Write a program that reads a string from theWrite a program that reads a string from the console and replaces all series of consecutiveconsole and replaces all series of consecutive identical letters with a single one. Example:identical letters with a single one. Example: ""aaaaabbbbbcdddeeeedssaaaaaaabbbbbcdddeeeedssaa""  ""abcdedsaabcdedsa".".
  • 70. Exercises (14)Exercises (14) 24.24. Write a program that reads a list of words,Write a program that reads a list of words, separated by spaces and prints the list in anseparated by spaces and prints the list in an alphabetical order.alphabetical order. 25.25. Write a program that extracts from given HTMLWrite a program that extracts from given HTML file its title (if available), and its body text withoutfile its title (if available), and its body text without the HTML tags. Example:the HTML tags. Example: <html><html> <head><title>News</title></head><head><title>News</title></head> <body><p><a href="http://academy.telerik.com">Telerik<body><p><a href="http://academy.telerik.com">Telerik Academy</a>aims to provide free real-world practicalAcademy</a>aims to provide free real-world practical training for young people who want to turn intotraining for young people who want to turn into skillful .NET software engineers.</p></body>skillful .NET software engineers.</p></body> </html></html>

Editor's Notes

  • #40: Introducing the StringBuffer Class StringBuffer represents strings that can be modified and extended at run time. The following example creates three new String objects, and copies all the characters each time a new String is created: String quote = &amp;quot;Fasten your seatbelts, &amp;quot;; quote = quote + &amp;quot;it’s going to be a bumpy night.&amp;quot;; It is more efficient to preallocate the amount of space required using the StringBuffer constructor, and its append() method as follows: StringBuffer quote = new StringBuffer(60); // alloc 60 chars quote.append(&amp;quot;Fasten your seatbelts, &amp;quot;);quote.append(&amp;quot; it’s going to be a bumpy night. &amp;quot;); StringBuffer also provides a number of overloaded insert() methods for inserting various types of data at a particular location in the string buffer. Instructor Note The example in the slide uses StringBuffer to reverse the characters in a string. A StringBuffer object is created, with the same length as the string. The loop traverses the String parameter in reverse order and appends each of its characters to the StringBuffer object by using append(). The StringBuffer therefore holds a reverse copy of the String parameter. At the end of the method, a new String object is created from the StringBuffer object, and this String is returned from the method.