Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
практика.docx
Скачиваний:
10
Добавлен:
09.06.2015
Размер:
79.45 Кб
Скачать

6. Строки

Строковые классы стандартной библиотеки C++ позволяют работать со строками как с обычными типами, не создающими проблем для пользователей.

Это означает, что строки можно копировать, присваивать и сравнивать как базовые типы, не беспокоясь о возможной нехватке памяти или размерах внутреннего блока, предназначенного для хранения символов. Тип string представляет последовательности символов способом, совместимым с алгоритмами и соглашениями STL. [1], [2]

Ниже представлен код программы, демонстрирующей работу класса string и применение к нему алгоритмов STL.

#include <string>

#include <iostream>

#include <fstream>

#include <cstring>

using namespace std;

int main()

{

ifstream in ("input_task3.txt");

string s;

getline(in,s);

in.close();

ofstream out ("output.txt");

out<<"input file: \n"<<s<<"\n\n";

/*substr. Выделение подстроки между первым и последним пробелами*/

string::size_type left_space = s.find (" ");

string::size_type right_space = s.rfind (" ");

string s_sub = s.substr (left_space, right_space - left_space);

out<<"substr (between first space and last

space):\n"<<s_sub<<"\n\n";

/*insert. Вставка подстроки в начало основной строки*/

string s_ins = s;

s_ins.insert (0, s_sub + " ");

out<<"insert of a substr in pos 0:\n"<<s_ins<<"\n\n";

/*append. Сложение строки и подстроки*/

string s_app = s;

s_app.append (s_sub);

out<<"append() (input string and substr)\n"<<s_app<<"\n\n";

/*copy. Копирование символов строки класса string в строку типа

char* */

char buf[500];

memset (buf, '\0', 500);

s.copy (buf, s.length(), 0);

out<<"copy() (input string to char)\n"<<buf<<"\n\n";

/*erase. Удаение подстроки из основной строки*/

string s_er=s;

s_er.erase(left_space, right_space - left_space);

out<<"erase substr between first space and last

space:\n"<<s_er<<"\n\n";

/*compare.Сравнивание строки и подстроки*/

int res=s.compare(s_sub);

out<<"compare (input string and substr):\n"<<res<<"\n\n";

/*swap.Меняет строки местами*/

string first("This is first string");

string second ("This is second string");

out<<"before swap():\n"<<first<<endl<<second<<endl;

first.swap (second);

out<<"after swap():\n"<<first<<endl<<second<<"\n\n";

/*find. Поиск первого вхожения слова 'Iterator', начиная слева*/

string::size_type pos_find = s.find("Iterator", 0);

out<<"first 'Iterator' at "<<pos_find;

/*rfind. Поиск первого вхожения слова 'Iterator', начиная справа*/

string::size_type pos_rfind = s.rfind("Iterator", s.length());

out<<"\nlast 'Iterator' at "<<pos_rfind<<"\n\n";

out.close();

return 0;

}

Содержимое входного файла:

There are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator.

Результат работы программы:

input file:

There are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator.

substr (between first space and last space):

are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access

insert of a substr in pos 0:

are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access There are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator.

append() (input string and substr)

There are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator. are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access

copy() (input string to char)

There are five kinds of iterators: Input Iterator, Output Iterator, Forward Iterator, Bidirectional Iterator, and Random Access Iterator.

erase substr between first space and last space:

There Iterator.

compare (input string and substr):

1

before swap():

This is first string

This is second string

after swap():

This is second string

This is first string

first 'Iterator' at 41

last 'Iterator' at 128