Активный
- Тема Автор
- #1
Руководство по использованию std::string для работы со строками в C++.
Создание и инициализация строк
Основные операции
Конкатенация строк
Поиск подстроки
Извлечение подстроки
Вставка и удаление
Сравнение строк
Преобразование типов
Итерация по строке
Работа с C-строками
Модификация регистра
Разделение строки
Обрезка пробелов
std::string предоставляет богатый набор методов для работы со строками. Эти примеры покрывают большинство задач по обработке строк.
Создание и инициализация строк
Код:
#include <string>
#include <iostream>
int main() {
// Пустая строка
std::string str1;
// Инициализация строковым литералом
std::string str2 = "Hello";
// Инициализация копией
std::string str3(str2);
// Инициализация подстрокой
std::string str4(str2, 0, 3); // "Hel"
// Инициализация несколькими символами
std::string str5(5, 'A'); // "AAAAA"
std::cout << str2 << std::endl;
std::cout << str3 << std::endl;
std::cout << str4 << std::endl;
std::cout << str5 << std::endl;
return 0;
}
Основные операции
Код:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello";
// Длина строки
std::cout << "Длина: " << str.length() << std::endl;
std::cout << "Размер: " << str.size() << std::endl;
// Проверка на пустоту
if (str.empty()) {
std::cout << "Строка пуста" << std::endl;
}
// Доступ к символам
std::cout << "Первый символ: " << str[0] << std::endl;
std::cout << "Последний символ: " << str.back() << std::endl;
// Изменение символа
str[0] = 'h';
std::cout << str << std::endl;
return 0;
}
Конкатенация строк
Код:
#include <string>
#include <iostream>
int main() {
std::string str1 = "Hello";
std::string str2 = " World";
// Оператор +
std::string str3 = str1 + str2;
std::cout << str3 << std::endl;
// Оператор +=
str1 += str2;
std::cout << str1 << std::endl;
// Добавление символа
str1 += '!';
std::cout << str1 << std::endl;
// Добавление C-строки
str1 += " How are you?";
std::cout << str1 << std::endl;
return 0;
}
Поиск подстроки
Код:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello World Hello";
// Поиск первого вхождения
size_t pos = str.find("World");
if (pos != std::string::npos) {
std::cout << "Найдено на позиции: " << pos << std::endl;
}
// Поиск последнего вхождения
pos = str.rfind("Hello");
if (pos != std::string::npos) {
std::cout << "Последнее вхождение на позиции: " << pos << std::endl;
}
// Поиск первого из символов
pos = str.find_first_of("aeiou");
std::cout << "Первая гласная на позиции: " << pos << std::endl;
// Поиск первого не из символов
pos = str.find_first_not_of("Helo ");
std::cout << "Первый не из набора на позиции: " << pos << std::endl;
return 0;
}
Извлечение подстроки
Код:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello World";
// Извлечение подстроки
std::string substr = str.substr(0, 5); // "Hello"
std::cout << substr << std::endl;
// С указанием только начальной позиции
substr = str.substr(6); // "World"
std::cout << substr << std::endl;
// Замена подстроки
str.replace(0, 5, "Hi");
std::cout << str << std::endl; // "Hi World"
return 0;
}
Вставка и удаление
Код:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello";
// Вставка в позицию
str.insert(5, " World");
std::cout << str << std::endl; // "Hello World"
// Вставка символа
str.insert(5, 1, ',');
std::cout << str << std::endl; // "Hello, World"
// Удаление символов
str.erase(5, 2); // Удалить 2 символа с позиции 5
std::cout << str << std::endl; // "Hello World"
// Удаление до конца
str.erase(5);
std::cout << str << std::endl; // "Hello"
return 0;
}
Сравнение строк
Код:
#include <string>
#include <iostream>
int main() {
std::string str1 = "Hello";
std::string str2 = "Hello";
std::string str3 = "World";
// Оператор ==
if (str1 == str2) {
std::cout << "Строки равны" << std::endl;
}
// Оператор !=
if (str1 != str3) {
std::cout << "Строки не равны" << std::endl;
}
// Метод compare
int result = str1.compare(str3);
if (result < 0) {
std::cout << "str1 меньше str3" << std::endl;
} else if (result > 0) {
std::cout << "str1 больше str3" << std::endl;
} else {
std::cout << "Строки равны" << std::endl;
}
return 0;
}
Преобразование типов
Код:
#include <string>
#include <iostream>
#include <sstream>
int main() {
// Число в строку (C++11)
int num = 123;
std::string str = std::to_string(num);
std::cout << str << std::endl;
// Строка в число
std::string numStr = "456";
int num2 = std::stoi(numStr);
std::cout << num2 << std::endl;
// Строка в float
std::string floatStr = "3.14";
float f = std::stof(floatStr);
std::cout << f << std::endl;
// Использование stringstream
std::stringstream ss;
ss << 789;
std::string result = ss.str();
std::cout << result << std::endl;
return 0;
}
Итерация по строке
Код:
#include <string>
#include <iostream>
int main() {
std::string str = "Hello";
// Обычная итерация
for (size_t i = 0; i < str.length(); i++) {
std::cout << str[i] << " ";
}
std::cout << std::endl;
// Итераторы
for (auto it = str.begin(); it != str.end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
// Range-based for loop
for (char c : str) {
std::cout << c << " ";
}
std::cout << std::endl;
// Обратная итерация
for (auto it = str.rbegin(); it != str.rend(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
return 0;
}
Работа с C-строками
Код:
#include <string>
#include <iostream>
#include <cstring>
int main() {
std::string str = "Hello World";
// Получение C-строки
const char* cstr = str.c_str();
std::cout << cstr << std::endl;
// Копирование в буфер
char buffer[100];
str.copy(buffer, str.length());
buffer[str.length()] = '\0';
std::cout << buffer << std::endl;
// Создание string из C-строки
const char* cstr2 = "Test";
std::string str2(cstr2);
std::cout << str2 << std::endl;
return 0;
}
Модификация регистра
Код:
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
int main() {
std::string str = "Hello World";
// Преобразование в верхний регистр
std::transform(str.begin(), str.end(), str.begin(), ::toupper);
std::cout << str << std::endl; // "HELLO WORLD"
// Преобразование в нижний регистр
std::transform(str.begin(), str.end(), str.begin(), ::tolower);
std::cout << str << std::endl; // "hello world"
return 0;
}
Разделение строки
Код:
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
int main() {
std::string str = "apple,banana,orange";
std::vector<std::string> tokens;
std::stringstream ss(str);
std::string token;
while (std::getline(ss, token, ',')) {
tokens.push_back(token);
}
for (const auto& t : tokens) {
std::cout << t << std::endl;
}
return 0;
}
Обрезка пробелов
Код:
#include <string>
#include <algorithm>
#include <iostream>
std::string trim(const std::string& str) {
size_t first = str.find_first_not_of(" \t\n\r");
if (first == std::string::npos) {
return "";
}
size_t last = str.find_last_not_of(" \t\n\r");
return str.substr(first, (last - first + 1));
}
int main() {
std::string str = " Hello World ";
std::string trimmed = trim(str);
std::cout << "[" << trimmed << "]" << std::endl;
return 0;
}
std::string предоставляет богатый набор методов для работы со строками. Эти примеры покрывают большинство задач по обработке строк.