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>
Ad

Recommended

String Handling
String Handling
Bharat17485
 
String handling(string class)
String handling(string class)
Ravi Kant Sahu
 
Arrays string handling java packages
Arrays string handling java packages
Sardar Alam
 
String and string buffer
String and string buffer
kamal kotecha
 
String handling session 5
String handling session 5
Raja Sekhar
 
Java Strings
Java Strings
RaBiya Chaudhry
 
Chapter 14 strings
Chapter 14 strings
Praveen M Jigajinni
 
String, string builder, string buffer
String, string builder, string buffer
SSN College of Engineering, Kalavakkam
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
String classes and its methods.20
String classes and its methods.20
myrajendra
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Strings in Java
Strings in Java
Abhilash Nair
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
String in python lecture (3)
String in python lecture (3)
Ali ٍSattar
 
Python strings
Python strings
Mohammed Sikander
 
Python strings presentation
Python strings presentation
VedaGayathri1
 
awesome groovy
awesome groovy
Paul King
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
concurrency gpars
concurrency gpars
Paul King
 
Manipulating strings
Manipulating strings
Jancypriya M
 
String in python use of split method
String in python use of split method
vikram mahendra
 
String.ppt
String.ppt
ajeela mushtaq
 
LectureNotes-04-DSA
LectureNotes-04-DSA
Haitham El-Ghareeb
 
groovy rules
groovy rules
Paul King
 
functional groovy
functional groovy
Paul King
 
String java
String java
774474
 
Strings part2
Strings part2
yndaravind
 
Erlang/OTP for Rubyists
Erlang/OTP for Rubyists
Sean Cribbs
 
String and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
More Pointers and Arrays
More Pointers and Arrays
emartinez.romero
 

More Related Content

What's hot (20)

Java string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
String classes and its methods.20
String classes and its methods.20
myrajendra
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
Strings in Java
Strings in Java
Abhilash Nair
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
String in python lecture (3)
String in python lecture (3)
Ali ٍSattar
 
Python strings
Python strings
Mohammed Sikander
 
Python strings presentation
Python strings presentation
VedaGayathri1
 
awesome groovy
awesome groovy
Paul King
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
concurrency gpars
concurrency gpars
Paul King
 
Manipulating strings
Manipulating strings
Jancypriya M
 
String in python use of split method
String in python use of split method
vikram mahendra
 
String.ppt
String.ppt
ajeela mushtaq
 
LectureNotes-04-DSA
LectureNotes-04-DSA
Haitham El-Ghareeb
 
groovy rules
groovy rules
Paul King
 
functional groovy
functional groovy
Paul King
 
String java
String java
774474
 
Strings part2
Strings part2
yndaravind
 
Erlang/OTP for Rubyists
Erlang/OTP for Rubyists
Sean Cribbs
 
Java string , string buffer and wrapper class
Java string , string buffer and wrapper class
SimoniShah6
 
String classes and its methods.20
String classes and its methods.20
myrajendra
 
Introduction to Java Strings, By Kavita Ganesan
Introduction to Java Strings, By Kavita Ganesan
Kavita Ganesan
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
Anwar Hasan Shuvo
 
String in python lecture (3)
String in python lecture (3)
Ali ٍSattar
 
Python strings presentation
Python strings presentation
VedaGayathri1
 
awesome groovy
awesome groovy
Paul King
 
GPars (Groovy Parallel Systems)
GPars (Groovy Parallel Systems)
Gagan Agrawal
 
concurrency gpars
concurrency gpars
Paul King
 
Manipulating strings
Manipulating strings
Jancypriya M
 
String in python use of split method
String in python use of split method
vikram mahendra
 
groovy rules
groovy rules
Paul King
 
functional groovy
functional groovy
Paul King
 
String java
String java
774474
 
Erlang/OTP for Rubyists
Erlang/OTP for Rubyists
Sean Cribbs
 

Viewers also liked (7)

String and string manipulation x
String and string manipulation x
Shahjahan Samoon
 
More Pointers and Arrays
More Pointers and Arrays
emartinez.romero
 
C string
C string
University of Potsdam
 
C programming - Pointers
C programming - Pointers
Wingston
 
C programming - String
C programming - String
Achyut Devkota
 
String c
String c
thirumalaikumar3
 
Pointers
Pointers
sarith divakar
 
Ad

Similar to 13 Strings and text processing (20)

16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
Module 6 - String Manipulation.pdf
Module 6 - String Manipulation.pdf
MegMeg17
 
13string in c#
13string in c#
Sireesh K
 
C# String
C# String
Raghuveer Guthikonda
 
String and string manipulation
String and string manipulation
Shahjahan Samoon
 
Strings in c#
Strings in c#
Dr.Neeraj Kumar Pandey
 
Strings Arrays
Strings Arrays
phanleson
 
05 c++-strings
05 c++-strings
Kelly Swanson
 
Csphtp1 15
Csphtp1 15
HUST
 
Computer programming 2 Lesson 12
Computer programming 2 Lesson 12
MLG College of Learning, Inc
 
L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
String in .net
String in .net
Larry Nung
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
Vahid Farahmandian
 
String handling(string class)
String handling(string class)
Ravi_Kant_Sahu
 
Java string handling
Java string handling
GaneshKumarKanthiah
 
OOPs difference faqs- 4
OOPs difference faqs- 4
Umar Ali
 
Strings
Strings
Nilesh Dalvi
 
Cs1123 9 strings
Cs1123 9 strings
TAlha MAlik
 
The string class
The string class
Syed Zaid Irshad
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
Abdul Samee
 
13 Strings and Text Processing
13 Strings and Text Processing
Intro C# Book
 
Module 6 - String Manipulation.pdf
Module 6 - String Manipulation.pdf
MegMeg17
 
13string in c#
13string in c#
Sireesh K
 
String and string manipulation
String and string manipulation
Shahjahan Samoon
 
Strings Arrays
Strings Arrays
phanleson
 
Csphtp1 15
Csphtp1 15
HUST
 
L13 string handling(string class)
L13 string handling(string class)
teach4uin
 
String in .net
String in .net
Larry Nung
 
Core C# Programming Constructs, Part 1
Core C# Programming Constructs, Part 1
Vahid Farahmandian
 
String handling(string class)
String handling(string class)
Ravi_Kant_Sahu
 
OOPs difference faqs- 4
OOPs difference faqs- 4
Umar Ali
 
Cs1123 9 strings
Cs1123 9 strings
TAlha MAlik
 
Ad

More from maznabili (20)

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

Recently uploaded (20)

High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
Tech-ASan: Two-stage check for Address Sanitizer - Yixuan Cao.pdf
caoyixuan2019
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Supporting the NextGen 911 Digital Transformation with FME
Supporting the NextGen 911 Digital Transformation with FME
Safe Software
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Creating Inclusive Digital Learning with AI: A Smarter, Fairer Future
Impelsys Inc.
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 

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.