Strings

35
Strings Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team http://academy.telerik.com Telerik Software Academy

description

Strings. Character sequences, C-strings and the C++ String class, Working with Strings. Learning & Development Team. http://academy.telerik.com. Telerik Software Academy. Table of Contents. What is string? String implementations in C++ Creating and Using Strings - PowerPoint PPT Presentation

Transcript of Strings

Page 1: Strings

StringsCharacter sequences, C-strings and the C+

+ String class, Working with Strings

Learning & Development Teamhttp://academy.telerik.com

Telerik Software Academy

Page 2: Strings

Table of Contents1. What is string?2. String implementations in C++3. Creating and Using Strings

Declaring, Creating, Reading and Printing

4. String functions Append, Insert, Erase, Find,

Substring5. Stringstream for converting strings

2

Page 3: Strings

What Is String?

Page 4: Strings

What Is String? Strings are sequences of characters

Each character is a Unicode symbol Represented by the char[] or string

Example:string s = "Hello, C++!";char c[] = "Hello, C++!";char g[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

4

Page 5: Strings

The System.String Class string comes from C++ and char[] is plain old C String objects contain an mutable

(read and write access) sequence of characters

Strings use Unicode to support multiple languages and alphabets

Strings are stored in the dynamic memory (managed heap)

string is reference type5

Page 6: Strings

The System.String Class (2)

String objects are like arrays of characters (char[]) Have fixed length – size() Elements can be accessed directly

by index The index is in the range [0...Length-1]string s = "Hello!";

int len = s.size(); // len = 6char ch = s[1]; // ch = 'e'

0 1 2 3 4 5H e l l o !

index = s[index] =

6

Page 7: Strings

Strings – First Examplestring s;char c[100];cin >> s >> c;cout << s << " " << c << endl;int len = strlen(c);cout << len;for(int i = 0; i < len; i++){ cout << endl << c[i];}cout << endl << s.size() << endl;for(int i = 0; i < s.size(); i++){ cout << s[i];}

7

Page 8: Strings

Strings – First ExampleLive Demo

Page 9: Strings

Creating and Using StringsDeclaring, Creating, Reading and

Printing

Page 10: Strings

Several ways of declaring string variables: Using the keyword string Using a char array

The above three declarations are equivalent

Declaring Strings

string str1;char[length] str2;char g[6] = {'H', 'e', 'l', 'l', 'o', '\0'};char g[] = "Hello";string str = "Hello";

10

Page 11: Strings

Creating Strings Before initializing a string variable has null value

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

string variable Assigning the value of another

string variable Assigning the result of operation of

type string The same can be done on char array

11

Page 12: Strings

Creating Strings (2) Not initialized variables has value of null

Assigning a string literal

Assigning from another string variable

Assigning from the result of string operation

string s; // s is equal to null

string s = "I am a string literal!";

string s2 = s;

string s = "I am " + name + "!";

12

Page 13: Strings

Constructors Several ways to create a string

string () - creates empty string - “” string (other_string) 

- creates a string identical to other_string

string (other_string, position, count ) - creates a string that contains count characters

string (count, character) - create a string containing character repeated count times

13

Page 14: Strings

Reading and Printing Strings

Reading strings from the console Include iostream Use cinstring s;cin >> s;

cout << s << s[i];

Printing strings to the console Use cout

14

Page 15: Strings

Creating StringsLive Demo

Page 16: Strings

String Constant Functions

Page 17: Strings

Constant Functions These do not modify the string

const char * data () - returns char array

unsigned int length () - returns the length of the string

unsigned int size ()   - returns the length of the string

bool empty () - returns true if the string is empty, otherwise returns false

17

Page 18: Strings

Constant FunctionsLive Demo

Page 19: Strings

String Operators

Page 20: Strings

String Operators These are available string operators Assign =  Append +=  Indexing []  Concatenate +  Equality == Inequality !=  Comparison <, >, <=, >= 

20

Page 21: Strings

String OperatorsLive Demo

Page 22: Strings

String Functions

Page 23: Strings

String Functions These are most common string functions void swap ( other_string )  string & append ( other_string )  string & insert ( position,

other_string )  string & erase ( position, count )  unsigned int find ( other_string,

position )  string substr ( position, count )  23

Page 24: Strings

String FunctionsLive Demo

Page 25: Strings

Converting Strings

Page 26: Strings

String Converting String converting is done through stringstream Include ssstream

It is used as cin and cout

26

stringstream ss;ss << 567;

int a;ss >> a; // a = 567

string str = ss.str();cout << str << endl; // str = “567”

Page 27: Strings

String ConvertingLive Demo

Page 28: Strings

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезанияASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET

курсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране

Николай Костов - блог за програмиранеC# курс, програмиране, безплатно

?? ? ?

??? ?

?

? ?

??

?

?

? ?

Questions?

?

Strings

http://algoacademy.telerik.com

Page 29: Strings

Exercises1. Describe the strings in C#. What is

typical for the string data type? Describe the most important methods of the String class.

2. Write a program that reads a string, reverses it and prints the result at the console.Example: "sample" "elpmas".

3. Write a program to check if in a given expression the brackets are put correctly.Example of correct expression:

((a+b)/5-d).Example of incorrect expression: )

(a+b)).

29

Page 30: Strings

Exercises (2)4. Write a program that finds how many

times a substring is contained in a given text (perform case insensitive search).

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

The result is: 9.

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

30

Page 31: Strings

Exercises (3)5. You are given a text. Write a program

that changes the text in all regions surrounded by the tags <upcase> and </upcase> to uppercase. The tags cannot be nested. Example:

The expected result:

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

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

31

Page 32: Strings

Exercises (4)6. Write a program that reads from the

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

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

32

Page 33: Strings

Exercises (5)8. Write a program that extracts from a

given text all sentences containing given word.

Example: The word is "in". The text is:

The expected result is:

Consider that the sentences are separated by "." and the words – by non-letter symbols.

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

We are living in a yellow submarine.We will move out of it in 5 days.

33

Page 34: Strings

Exercises (6)9. We are given a string containing a list

of forbidden words and a text containing some of these words. Write a program that replaces the forbidden words with asterisks. Example:

Words: "PHP, CLR, Microsoft"The expected result:

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

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

34

Page 35: Strings

Exercises (7)10. Write a program that parses an URL

address given in the format:

and extracts from it the [protocol], [server] and [resource] elements. For example from the URL http://www.devbg.org/forum/index.php the following information should be extracted:

[protocol] = "http"[server] = "www.devbg.org"[resource] = "/forum/index.php"

[protocol]://[server]/[resource]

35