70
Strings and Text Strings and Text Processing Processing Processing and Manipulating Text Processing and Manipulating Text Information Information Svetlin Nakov Svetlin Nakov Telerik Telerik Corporation Corporation www.telerik. com

13. Strings and Text Processing

Embed Size (px)

DESCRIPTION

Basic Operations with Strings – Comparison, Concatenation, Extracting substring, Searching More Operations with Strings – Replacing Substrings, Deleting Substrings Building Strings: The Effective Way Formatting Strings Exercises: Working with Strings and Text Processing

Citation preview

Page 1: 13. Strings and Text Processing

Strings and Text Strings and Text ProcessingProcessing

Processing and Manipulating Text Processing and Manipulating Text InformationInformation

Svetlin NakovSvetlin NakovTelerik Telerik

CorporationCorporationwww.telerik.com

Page 2: 13. Strings and Text Processing

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 Declaring, Creating, Reading and PrintingPrinting

3.3. Manipulating StringsManipulating Strings

Comparing, Concatenating, Searching, Comparing, Concatenating, Searching, Extracting Substrings, SplittingExtracting Substrings, Splitting

4.4. Other String OperationsOther String Operations

Replacing Substrings, Deleting Replacing Substrings, Deleting Substrings, Changing Character Casing, Substrings, Changing Character Casing, TrimmingTrimming

Page 3: 13. Strings and Text Processing

Table of Contents (2)Table of Contents (2)

5.5. Building and Modifying StringsBuilding and Modifying Strings

Using Using StringBuilderStringBuilder Class Class

6.6. Formatting StringsFormatting Strings

Page 4: 13. Strings and Text Processing

What Is String?What Is String?

Page 5: 13. Strings and Text Processing

What Is String?What Is String? Strings are sequences of Strings are sequences of

characterscharacters Each character is a Unicode symbolEach character is a Unicode symbol Represented by the Represented by the stringstring data data

type in C# (type in C# (System.StringSystem.String)) Example:Example:

string s = "Hello, C#";string s = "Hello, C#";

HH ee ll ll oo ,, CC ##ss

Page 6: 13. Strings and Text Processing

The The System.StringSystem.String Class Class Strings are represented by Strings are represented by System.StringSystem.String objects in .NET objects in .NET FrameworkFramework

String objects contain an immutable String objects contain an immutable (read-only) sequence of characters(read-only) sequence of characters

Strings use Unicode in to support Strings use Unicode in to support multiple languages and alphabetsmultiple languages and alphabets

Strings are stored in the dynamic Strings are stored in the dynamic memory (memory (managed heapmanaged heap))

System.StringSystem.String is reference type is reference type

Page 7: 13. Strings and Text Processing

The The System.StringSystem.String Class Class (2)(2)

String objects are like arrays of String objects are like arrays of characters (characters (char[]char[]))

Have fixed length (Have fixed length (String.LengthString.Length))

Elements can be accessed directly Elements can be accessed directly by indexby index

The index is in the range [The index is in the range [00......Length-Length-11]]

string s = "Hello!";string s = "Hello!";int len = s.Length; // len = 6int len = s.Length; // len = 6char 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] =

Page 8: 13. Strings and Text Processing

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}", Console.WriteLine("s.Length = {0}", s.Length);s.Length); for (int i = 0; i < s.Length; i++)for (int i = 0; i < s.Length; i++) {{ Console.WriteLine("s[{0}] = {1}", i, Console.WriteLine("s[{0}] = {1}", i, s[i]);s[i]); }}}}

Page 9: 13. Strings and Text Processing

Strings – First Strings – First ExampleExampleLive DemoLive Demo

Page 10: 13. Strings and Text Processing

Creating and Using Creating and Using StringsStrings

Declaring, Creating, Reading and Declaring, Creating, Reading and PrintingPrinting

Page 11: 13. Strings and Text Processing

Declaring StringsDeclaring Strings There are two ways of declaring There are two ways of declaring

string variables:string variables: UsingUsing thethe C# C# keywordkeyword stringstring

Using the .NET's fully qualified Using the .NET's fully qualified class name class name System.StringSystem.String

The above three declarations are The above three declarations are equivalentequivalent

string str1;string str1;System.String str2;System.String str2;String str3;String str3;

Page 12: 13. Strings and Text Processing

Creating StringsCreating Strings

Before initializing a string variable Before initializing a string variable has has nullnull valuevalue

Strings can be initialized by:Strings can be initialized by: Assigning a string literal to the Assigning a string literal to the

string variablestring variable Assigning the value of another Assigning the value of another

string variablestring variable Assigning the result of operation of Assigning the result of operation of

type stringtype string

Page 13: 13. Strings and Text Processing

Creating Strings (2)Creating Strings (2)

Not initialized variables has value of Not initialized variables has value of nullnull

Assigning a string literalAssigning a string literal

Assigning from another string Assigning from another string variablevariable

Assigning from the result of string Assigning from the result of string operationoperation

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();

Page 14: 13. Strings and Text Processing

Reading and Printing Reading and Printing StringsStrings

Reading strings from the consoleReading strings from the console Use the method Use 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 methods Use the methods Write()Write() and and WriteLine()WriteLine()

Page 15: 13. Strings and Text Processing

Reading and Printing Reading and Printing StringsStringsLive DemoLive Demo

Page 16: 13. Strings and Text Processing

Comparing, Concatenating, Comparing, Concatenating, Searching, Extracting Substrings, Searching, Extracting Substrings,

SplittingSplitting

Manipulating Manipulating StringsStrings

Page 17: 13. Strings and Text Processing

Comparing StringsComparing Strings A number of ways exist to compare A number of ways exist to compare

two strings:two 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);

Page 18: 13. Strings and Text Processing

Comparing Strings (2)Comparing Strings (2) Equality checking by operator Equality checking by operator ====

Performs case-sensitive comparePerforms case-sensitive compare

Using the case-sensitive Using the case-sensitive Equals()Equals() methodmethod The same effect like the operator The same effect like the operator ====

if (str1 == str2)if (str1 == str2){{ … …}}

if (str1.Equals(str2))if (str1.Equals(str2)){{ … …}}

Page 19: 13. Strings and Text Processing

Comparing Strings – Comparing Strings – Example Example

Finding the first string in a Finding the first string in a lexicographical order from a given list lexicographical order from a given list of strings: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) < if (String.Compare(currentTown, firstTown) < 0)0) {{ firstTown = currentTown;firstTown = currentTown; }}}}Console.WriteLine("First town: {0}", firstTown);Console.WriteLine("First town: {0}", firstTown);

Page 20: 13. Strings and Text Processing

Live DemoLive Demo

Comparing Comparing StringsStrings

Page 21: 13. Strings and Text Processing

Concatenating StringsConcatenating Strings

There are two ways to combine There are two ways to combine strings:strings:

Using the Using the Concat()Concat() method method

Using the Using the ++ or the or the +=+= operators operators

Any object can be appended to Any object can be appended to stringstring

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"

Page 22: 13. Strings and Text Processing

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

Page 23: 13. Strings and Text Processing

Live Demo

Concatenating Concatenating StringsStrings

Page 24: 13. Strings and Text Processing

Searching in StringsSearching in Strings

Finding a character or substring Finding a character or substring within given stringwithin given string

First occurrenceFirst occurrence

First occurrence starting at given First occurrence starting at given positionposition

Last occurrenceLast occurrence

IndexOf(string str)IndexOf(string str)

IndexOf(string str, int startIndex)IndexOf(string str, int startIndex)

LastIndexOf(string)LastIndexOf(string)

Page 25: 13. Strings and Text Processing

Searching in Strings – Searching in Strings – ExampleExample

string str = "C# Programming Course";string str = "C# Programming Course";int index = str.IndexOf("C#"); // index = 0int index = str.IndexOf("C#"); // index = 0index = str.IndexOf("Course"); // index = 15index = str.IndexOf("Course"); // index = 15index = 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 foundindex = str.IndexOf("ram"); // index = 7index = str.IndexOf("ram"); // index = 7index = str.IndexOf("r"); // index = 4index = str.IndexOf("r"); // index = 4index = str.IndexOf("r", 5); // index = 7index = str.IndexOf("r", 5); // index = 7index = 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] =

Page 26: 13. Strings and Text Processing

Live DemoLive Demo

SearchiSearchingng in in

StringsStrings

Page 27: 13. Strings and Text Processing

Extracting SubstringsExtracting Substrings Extracting substringsExtracting substrings

str.Substring(int startIndex, int str.Substring(int startIndex, int length)length)

str.Substring(int startIndex)str.Substring(int startIndex)

string filename = @"C:\Pics\Rila2009.jpg";string filename = @"C:\Pics\Rila2009.jpg";string name = filename.Substring(8, 8);string name = filename.Substring(8, 8);// name is Rila2009// name is Rila2009

string filename = @"C:\Pics\Summer2009.jpg";string filename = @"C:\Pics\Summer2009.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

Page 28: 13. Strings and Text Processing

Live DemoLive Demo

Extracting Extracting SubstringsSubstrings

Page 29: 13. Strings and Text Processing

Splitting StringsSplitting Strings

To split a string by given separator(s) To split a string by given separator(s) use the following method:use the 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);}}

Page 30: 13. Strings and Text Processing

Live DemoLive Demo

Splitting StringsSplitting Strings

Page 31: 13. Strings and Text Processing

Other String Other String OperationsOperationsReplacing Substrings, Deleting Replacing Substrings, Deleting

Substrings, Changing Character Substrings, Changing Character Casing, TrimmingCasing, Trimming

Page 32: 13. Strings and Text Processing

Replacing and Deleting Replacing and Deleting SubstringsSubstrings

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 The result is new string (strings are

immutable)immutable)

ReRemovemove((indexindex,, lengthlength)) – deletes part of a – deletes part of a string and produces new string as resultstring and 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

Page 33: 13. Strings and Text Processing

Changing Character Changing Character CasingCasing

Using method Using method ToLower()ToLower()

Using method Using method ToUpper()ToUpper()

string alpha = "aBcDeFg";string alpha = "aBcDeFg";string lowerAlpha = alpha.ToLower(); // abcdefgstring lowerAlpha = alpha.ToLower(); // abcdefgConsole.WriteLine(lowerAlpha);Console.WriteLine(lowerAlpha);

string alpha = "aBcDeFg";string alpha = "aBcDeFg";string upperAlpha = alpha.ToUpper(); // ABCDEFGstring upperAlpha = alpha.ToUpper(); // ABCDEFGConsole.WriteLine(upperAlpha);Console.WriteLine(upperAlpha);

Page 34: 13. Strings and Text Processing

Trimming White SpaceTrimming White Space

Using method Using method Trim()Trim()

Using method Using method Trim(charsTrim(chars))

Using Using TrimTrimStartStart()() and and 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 = " \t\nHello!!! \n";string s = " \t\nHello!!! \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# "

Page 35: 13. Strings and Text Processing

Other String Other String OperationsOperations

Live DemoLive Demo

Page 36: 13. Strings and Text Processing

Building and Modifying Building and Modifying StringsStrings

Using Using StringBuilder StringBuilder CClasslass

Page 37: 13. Strings and Text Processing

Constructing StringsConstructing Strings Strings are immutableStrings are immutable

CConcat()oncat(), , RReplace()eplace(), , TTrim()rim(), ..., ... return new string, do not modify return new string, do not modify the old onethe old one

Do not use "Do not use "++" for strings in a " for strings in a loop!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 bad Very bad practice. practice.

Avoid this!Avoid this!

Page 38: 13. Strings and Text Processing

Slow Building Strings Slow Building Strings with +with +Live DemoLive Demo

Page 39: 13. Strings and Text Processing

Changing the Contents of Changing the Contents of a String – a String – StringBuilderStringBuilder

Use the Use the System.Text.StringBuilderSystem.Text.StringBuilder class for modifiable strings of class for modifiable strings of characters:characters:

Use Use StringBuilderStringBuilder if you need to keep if you need to keep adding characters to a stringadding characters 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();}}

Page 40: 13. Strings and Text Processing

The The StringBuildeStringBuilder Classr Class

StringBuilderStringBuilder keeps a buffer keeps a buffer memory, allocated in advancememory, allocated in advance Most operations use the buffer Most operations use the buffer

memory and do not allocate new memory and do not allocate new objectsobjects

HH ee ll ll oo ,, CC ## !!StringBuilderStringBuilder::

Length=9Length=9Capacity=15Capacity=15

CapacityCapacity

used used bufferbuffer(Length)(Length)

unused unused bufferbuffer

Page 41: 13. Strings and Text Processing

The The StringBuildeStringBuilder Class r Class (2)(2)

StringBuilder(int capacity)StringBuilder(int capacity) constructor allocates in advance constructor allocates in advance buffer memory of a given sizebuffer memory of a given size

By default 16 characters are allocatedBy default 16 characters are allocated CapacityCapacity holds the currently allocated holds the currently allocated

space (in characters)space (in characters) this[int index]this[int index] (indexer in C#) gives (indexer in C#) gives

access to the char value at given access to the char value at given positionposition

LengthLength holds the length of the string holds the length of the string in the bufferin the buffer

Page 42: 13. Strings and Text Processing

The The StringBuildeStringBuilder Class r Class (3)(3)

Append(…)Append(…) appends string or another object appends string or another object after the last character in the bufferafter the last character in the buffer

RemoveRemove(int start(int startIndexIndex,, int int lengthlength)) removes removes the characters in given rangethe characters in given range

IInsert(int nsert(int indexindex,, sstring str)tring str) inserts given inserts 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 replaces all occurrences of a substring with new stringnew string

TToString()oString() converts the converts the StringBuilderStringBuilder to to StringString

Page 43: 13. Strings and Text Processing

StringBuilderStringBuilder – Example – Example Extracting all capital letters from a Extracting all capital letters from a

stringstringpublic 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();}}

Page 44: 13. Strings and Text Processing

How the How the ++ Operator Does Operator Does String Concatenations?String Concatenations?

Consider following string Consider following string concatenation:concatenation:

It is equivalent to this code:It is equivalent to this code:

Actually several new objects are Actually several new objects are created and leaved to the garbage created and leaved to the garbage collectorcollector What happens when using What 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();

Page 45: 13. Strings and Text Processing

Using Using StringBuilderStringBuilderLive DemoLive Demo

Page 46: 13. Strings and Text Processing

Formatting Formatting StringsStringsUsing Using ToString()ToString() and and

String.Format()String.Format()

Page 47: 13. Strings and Text Processing

Method Method ToString()ToString() All classes have public virtual All classes have public virtual

method method ToString()ToString() Returns a human-readable, culture-Returns a human-readable, culture-

sensitive string representing the sensitive string representing the objectobject

Most .NET Framework types have Most .NET Framework types have own implementation of own implementation of ToString()ToString()

intint, , floatfloat, , boolbool, , DateTimeDateTimeint 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

Page 48: 13. Strings and Text Processing

Method Method ToString(formatToString(format))

We can apply specific formatting We can apply specific formatting when converting objects to stringwhen converting objects to string ToString(foToString(forrmatString)matString) method method

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 Bulgarians = 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 %

Page 49: 13. Strings and Text Processing

Formatting StringsFormatting Strings The formatting strings are different for The formatting strings are different for

the different typesthe different 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 – currency (according to current culture)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)

Page 50: 13. Strings and Text Processing

Method Method String.Format()String.Format()

Applies Applies templatestemplates for formatting for formatting stringsstrings Placeholders are used for dynamic Placeholders are used for dynamic

texttext Like Like 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.

Page 51: 13. Strings and Text Processing

Composite FormattingComposite Formatting

The placeholders in the composite The placeholders in the composite formatting strings are specified as formatting strings are specified as follows: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

Page 52: 13. Strings and Text Processing

Formatting DatesFormatting Dates Dates have their own formatting Dates have their own formatting

stringsstrings

dd, , dddd – – day (with/without leading day (with/without leading zero)zero)

MM, , MMMM – – monthmonth

yyyy, , yyyyyyyy – – year (2 or 4 digits)year (2 or 4 digits)

hh, , HHHH, , mm, , mmmm, , ss, , ssss – – hour, minute, hour, minute, secondsecond

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

Page 53: 13. Strings and Text Processing

Formatting Formatting StringsStringsLive DemoLive Demo

Page 54: 13. Strings and Text Processing

SummarySummary Strings are immutable sequences of Strings are immutable sequences of

characters (instances of characters (instances of System.StringSystem.String)) Declared by the keyword Declared by the keyword stringstring in C# in C#

Can be initialized by string literalsCan be initialized by string literals

Most important string processing Most important string processing members are: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()

Page 55: 13. Strings and Text Processing

Summary (2)Summary (2) Objects can be converted to strings Objects can be converted to strings

and can be formatted in different and can be formatted in different styles (using styles (using ToStringToString()() method) method)

Strings can be constructed by Strings can be constructed by using placeholders and formatting using placeholders and formatting strings (strings (String.FormatString.Format(…)(…)))

Page 56: 13. Strings and Text Processing

Strings and Text Strings and Text ProcessingProcessing

Questions?Questions?

http://academy.telerik.com

Page 57: 13. Strings and Text Processing

ExercisesExercises

1.1. Describe the strings in C#. What is typical Describe the strings in C#. What is typical for the for the stringstring data type? Describe the most data type? Describe the most important methods of the important methods of the StringString class. class.

2.2. Write a program that reads a string, Write a program that reads a string, reverses it and prints it on the console. reverses it and prints it on the console. Example: "sample" Example: "sample" " "elpmaselpmas".".

3.3. Write a program to check if in a given Write a program to check if in a given expression the brackets are put correctly. expression the brackets are put correctly. Example of correct expression: Example of correct expression: ((a+b)/5-d)((a+b)/5-d). . Example of incorrect expression: Example of incorrect expression: )(a+b)))(a+b))..

Page 58: 13. Strings and Text Processing

Exercises (2)Exercises (2)

4.4. Write a program that finds how many Write a program that finds how many times a substring is contained in a times a substring is contained in a given text (perform case insensitive given text (perform case insensitive search).search).

Example: The target substring is Example: The target substring is ""inin". The text is as follows:". The text is as follows:

The result is: 9.The result is: 9.

We are living in an yellow submarine. We don't We are living in an yellow submarine. We don't have anything else. Inside the submarine is have anything else. Inside the submarine is very tight. So we are drinking all the day. We very tight. So we are drinking all the day. We will move out of it in 5 days.will move out of it in 5 days.

Page 59: 13. Strings and Text Processing

Exercises (3)Exercises (3)

5.5. You are given a text. Write a program You are given a text. Write a program that changes the text in all regions that changes the text in all regions surrounded by the tagssurrounded by the tags <upcase><upcase> andand </upcase></upcase> to uppercase. The tags to uppercase. The tags cannot be nested. Example:cannot be nested. Example:

The expected result:The expected result:

We are living in a <upcase>yellow We are living in a <upcase>yellow submarine</upcase>. We don't have submarine</upcase>. We don't have <upcase>anything</upcase> else.<upcase>anything</upcase> else.

We are living in a YELLOW SUBMARINE. We don't We are living in a YELLOW SUBMARINE. We don't have ANYTHING else.have ANYTHING else.

Page 60: 13. Strings and Text Processing

Exercises (4)Exercises (4)

6.6. Write a program that reads from the console a Write a program that reads from the console a string of maximum 20 characters. If the length string of maximum 20 characters. If the length of the string is less than 20, the rest of the of the string is less than 20, the rest of the characters should be filled with '*'. Print the characters should be filled with '*'. Print the result string into the console.result string into the console.

7.7. Write a program that encodes and decodes a Write a program that encodes and decodes a string using given encryption key (cipher). The string using given encryption key (cipher). The key consists of a sequence of characters. The key consists of a sequence of characters. The encoding/decoding is done by performing XOR encoding/decoding is done by performing XOR (exclusive or) operation over the first letter of (exclusive or) operation over the first letter of the string with the first of the key, the second the string with the first of the key, the second – with the second, etc. When the last key – with the second, etc. When the last key character is reached, the next is the first.character is reached, the next is the first.

Page 61: 13. Strings and Text Processing

Exercises (5)Exercises (5)

8.8. Write a program that extracts from a given Write a program that extracts from a given text all sentences containing given word.text all 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 Consider that the sentences are separated by "separated by ".." and the words – by non-" and the words – by non-letter symbols.letter symbols.

We are living in a yellow submarine. We don't We are living in a yellow submarine. We don't have anything else. Inside the submarine is have anything else. Inside the submarine is very tight. So we are drinking all the day. We very tight. So we are drinking all the day. We will move out of it in 5 days.will move out 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.

Page 62: 13. Strings and Text Processing

Exercises (6)Exercises (6)

9.9. We are given a string containing a list We are given a string containing a list of forbidden words and a text of forbidden words and a text containing some of these words. Write containing some of these words. Write a program that replaces the forbidden a program that replaces the forbidden words with asterisks. Example:words with asterisks. Example:

Words: "PHP, CLR, Microsoft"Words: "PHP, CLR, Microsoft"

The expected result:The expected result:

Microsoft announced its next generation PHP Microsoft announced its next generation PHP compiler today. It is based on .NET Framework compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language 4.0 and is implemented as a dynamic language in CLR.in CLR.

********* announced its next generation *** ********* announced its next generation *** compiler today. It is based on .NET Framework compiler today. It is based on .NET Framework 4.0 and is implemented as a dynamic language 4.0 and is implemented as a dynamic language in ***.in ***.

Page 63: 13. Strings and Text Processing

Exercises (7)Exercises (7)

10.10. Write a program that converts a string to Write a program that converts a string to a sequence of C# Unicode character a sequence of C# Unicode character literals. Use format strings. Sample input:literals. Use format strings. Sample input:

Expected output:Expected output:

11.11. Write a program that reads a number and Write a program that reads a number and prints it as a decimal number, prints it as a decimal number, hexadecimal number, percentage and in hexadecimal number, percentage and in scientific notation. Format the output scientific notation. Format the output aligned right in 15 symbols.aligned right in 15 symbols.

Hi!Hi!

\u0048\u0069\u0021\u0048\u0069\u0021

Page 64: 13. Strings and Text Processing

Exercises (8)Exercises (8)

12.12. Write a program that parses an URL Write a program that parses an URL address given in the format:address given in the format:

and extracts from it the and extracts from it the [protocol][protocol], , [server][server] andand [resource][resource] elements. For elements. For example from the URL example from the URL http://www.devbg.org/forum/index.phphttp://www.devbg.org/forum/index.php the the following information should be extracted: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]

Page 65: 13. Strings and Text Processing

Exercises (9)Exercises (9)

13.13. Write a program that reverses the Write a program that reverses the words in given sentence.words in given sentence.

Example: "C# is not C++, not PHP and Example: "C# is not C++, not PHP and not Delphi!" not Delphi!" "Delphi not and PHP, "Delphi not and PHP, not C++ not is C#!".not C++ not is C#!".

14.14. A dictionary is stored as a sequence of A dictionary is stored as a sequence of text lines containing words and their text lines containing words and their explanations. Write a program that explanations. Write a program that enters a word and translates it by enters a word and translates it by using the dictionary. Sample using the dictionary. Sample dictionary:dictionary:

.NET – platform for applications from .NET – platform for applications from MicrosoftMicrosoftCLR – managed execution environment for .NETCLR – managed execution environment for .NETnamespace – hierarchical organization of namespace – hierarchical organization of classesclasses

Page 66: 13. Strings and Text Processing

Exercises (10)Exercises (10)

15.15. Write a program that replaces in a Write a program that replaces in a HTML document given as string all the HTML document given as string all the tags tags <a <a hrefhref="…">…</a>="…">…</a> with with corresponding tags corresponding tags [URL=…]…/URL][URL=…]…/URL]. . Sample HTML fragment:Sample HTML fragment:<p>Please visit <a <p>Please visit <a href="http://academy.telerik. com">our href="http://academy.telerik. com">our site</a> to choose a training course. Also site</a> to choose a training course. Also visit <a href="www.devbg.org">our forum</a> to visit <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 com]our site[/URL] to choose a training course. Also visit [URL=www.devbg.org]our course. Also visit [URL=www.devbg.org]our forum[/URL] to discuss the courses.</p>forum[/URL] to discuss the courses.</p>

Page 67: 13. Strings and Text Processing

Exercises (11)Exercises (11)

16.16. Write a program that reads two dates in Write a program that reads two dates in the format: the format: day.month.yearday.month.year and calculates and calculates the number of days between them. the number of days between them. Example:Example:

17.17. Write a program that reads a date and Write a program that reads a date and time given in the format: time given in the format: day.month.yearday.month.year hour:minute:secondhour:minute:second and prints the date and prints the date and time after 6 hours and 30 minutes (in and time after 6 hours and 30 minutes (in the same format).the same format).

Enter the first date: 27.02.2006Enter the first date: 27.02.2006Enter the second date: 3.03.2004Enter the second date: 3.03.2004Distance: 4 daysDistance: 4 days

Page 68: 13. Strings and Text Processing

Exercises (12)Exercises (12)

18.18. Write a program for extracting all the Write a program for extracting all the email addresses from given text. All email addresses from given text. All substrings that match the format substrings that match the format <identifier>@<host>… <domain><identifier>@<host>… <domain> should be should be recognized as emails.recognized as emails.

19.19. Write a program that extracts from a Write a program that extracts from a given text all the dates that match the given text all the dates that match the format format DD.MM.YYYYDD.MM.YYYY. Display them in the . Display them in the standard date format for Canada.standard date format for Canada.

20.20. Write a program that extracts from a Write a program that extracts from a given text all palindromes, e.g. "given text all palindromes, e.g. "ABBAABBA", ", ""lamallamal", "", "exeexe".".

Page 69: 13. Strings and Text Processing

Exercises (13)Exercises (13)

21.21. Write a program that reads a string from Write a program that reads a string from the console and prints all different letters the console and prints all different letters in the string along with information how in the string along with information how many times each letter is found. many times each letter is found.

22.22. Write a program that reads a string from Write a program that reads a string from the console and lists all different words in the console and lists all different words in the string along with information how the string along with information how many times each word is found.many times each word is found.

23.23. Write a program that reads a string from Write a program that reads a string from the console and replaces all series of the console and replaces all series of consecutive identical letters with a single consecutive identical letters with a single one. Example: "one. Example: "aaaaabbbbbcdddeeeedssaaaaaaabbbbbcdddeeeedssaa" " " "abcdedsaabcdedsa".".

Page 70: 13. Strings and Text Processing

Exercises (14)Exercises (14)

24.24. Write a program that reads a list of Write a program that reads a list of words, separated by spaces and prints words, separated by spaces and prints the list in an alphabetical order.the list in an alphabetical order.

25.25. Write a program that extracts from Write a program that extracts from given HTML file its title (if available), given HTML file its title (if available), and its body text without the HTML and its body text without the HTML tags. Example:tags. Example:<html><html>

<head><title>News</title></head><head><title>News</title></head> <body><p><a <body><p><a href="http://academy.telerik.com">Telerikhref="http://academy.telerik.com">Telerik Academy</a>aims to provide free real-world Academy</a>aims to provide free real-world practicalpractical 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>