character sequences, c-strings and the c++ string class, working with strings learning &...

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

Upload: barbara-powell

Post on 17-Dec-2015

249 views

Category:

Documents


1 download

TRANSCRIPT

StringsCharacter sequences, C-strings and the C+

+ String class, Working with Strings

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

Telerik Software Academy

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,

Substring

5. Stringstream for converting strings

2

What Is String?

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

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

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 5

H e l l o !

index =

s[index] =

6

Strings – First Example

string 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

Strings – First ExampleLive Demo

Creating and Using StringsDeclaring, Creating, Reading and

Printing

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

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

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

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

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

Creating StringsLive Demo

String Constant Functions

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

Constant FunctionsLive Demo

String Operators

String Operators These are available string operators Assign = 

Append += 

Indexing [] 

Concatenate + 

Equality ==

Inequality != 

Comparison <, >, <=, >= 20

String OperatorsLive Demo

String Functions

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

String FunctionsLive Demo

Converting 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”

String ConvertingLive Demo

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

програмиране за деца – безплатни курсове и уроцибезплатен 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, PhoneGap

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

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Strings

http://algoacademy.telerik.com

Exercises

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

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

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

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

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

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

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