Руководство C/C++ String
View more Tutorials:
В C++ имеется два вида строка (string), строки в стиле C (C-style string), и строки в стиле C++ (C++-Style string).
C-Style string это массивы знаков, но есть разные функции использующиеся для строк, например добавление в строки, нахождение длины строк, и так же проверка соответствия строк с регулярным выражением (regular expression).
Определение строки будет то, что содержит более одного знака связанных друг с другом. Например, "this" это строка. При этом, один знак не считается строкой, несмотря на то, что они используются как строки.
String это массив знаков. Используйте ковычки для отметки строки букв (string literals)
// Declare a C-Style String. char mystring[] = { 't', 'h', 'i', 's', ' ', 'i', 's' ,' ', 't', 'e', 'x', 't', '\0'}; // This is a string literal. char mystring[] = "this is text'';
StringLiteralExample.cpp
#include <stdio.h> int main() { // Declare a String literal. char s1[] = "What is this"; // Print out the string printf("Your string = %s", s1); fflush(stdout); return 0; }
Результаты запуска примера:

- char mystr[] = "what is this";
Строка string выше имеет 12 знаков, для объявления того string в C вам нужно объявить массив знаков с 13 элементами, запомните, что последний элемент в массиве это знак null (код '\0'), это означает конец string. Этот последний знак не имеет значение в вашей строке, но он нужен для программ C, например указатель (pointer) указывает на позицию string он будет стоять в позиции первого знака, и чтобы получить содержание строки, программа загрузит следующий элемент до тех пор, когда не встретит знак null.
Заметка:
В случае если у вас есть массив знаков и при этом есть знак null, который не находится в конце массива, или много знаков null в массиве. Но C будет считать, что этот массив содержит string, включая первый знак до первого знака null в массиве.![]()
Следующий пример объявляет массив знаков с 100 элементами использующиеся для хранения текста, который был введен пользователем с клавиатуры. В этом случе все знаки введенной строки будут прикреплены первому элементу в массиве и затем знак null. И следующие элементы не могут быть прикреплены.

StringFromKeyboardExample.cpp
#include <stdio.h> int main() { // Declare an array of characters with 100 elements, // used to store user input string from the keyboard. char s1[100]; printf("Enter your string: \n"); fflush(stdout); // scanf function wait user input from the keyboard. // (Press enter to end). // It will scan to get a string and assigned to the variable s1. // (%s: scan a string does not contain spaces) scanf("%s", s1); printf("Your string = %s", s1); fflush(stdout); return 0; }
Результаты запуска примера:

C предоставляет некоторые функции для работы с String. Он располагается в стандартной библиотеке <string.h>. Далее я перечислю некоторые общие функции C связанные с string (не все).
Некоторые функции для String.
Название функции | Описание |
size_t strlen(const char *str) | Вычисляет длину строки, не считая завершающий символ (символ null) |
char *strcpy(char *dest, const char *src) | Копирует строку 'src' в 'dest'. |
int strcmp(const char *str1, const char *str2) | Сравнивает 2 строки данные параметром указателя str1, и str2. Возвращает целое число > 0 то есть str1 > str2. И = 0 это 2 одинаковые строки, наоборот str1 < str2. |
char *strcat(char *dest, const char *src) | Добавляет строку, на которую указывает src к концу строки на которую указывает dest. |
char *strchr(const char *str, int c) | Ищет первое происхождение символа c (an unsigned char) в строке на которую указывает аргумент str. |
StringFunctionsExample.cpp
#include <stdio.h> // Using string library. #include <string.h> int main() { // Declare a string literal. char s1[] = "This is "; // Declare a C-Style string // (With null character at the end). char s2[] = { 't', 'e', 'x', 't', '\0' }; // Function: size_t strlen(const char *str) // strlen funtion return length of the string. // site_t: is unsigned integer data type. size_t len1 = strlen(s1); size_t len2 = strlen(s2); printf("Length of s1 = %d \n", len1); printf("Length of s2 = %d \n", len2); // Declare an array with 100 elements. char mystr[100]; // Function: char *strcpy(char *dest, const char *src) // copy s1 to mystr. strcpy(mystr, s1); // Function: char *strcat(char *dest, const char *src) // Using strcat function to concatenate two strings strcat(mystr, s2); // Print out content of mystr. printf("Your string = %s", mystr); fflush(stdout); return 0; }
Результаты запуска примера:

C++ предоставляет вам класс string, который помогает вам легко работать со строкам. Методы, которые class string предоставляет так же поддерживает для работы с C-Style string.
Чтобы использовать string вам нужно объявить директивы процессора (Preprocessor Directives) #include <string> и объявить использование пространства с названием std.
// Declare Preprocessor Directives #include <string> // Declare to use the namespace std. using namespace std;
Объявить string:
// Declare a string object. string mystring = "Hello World"; // If you do not declare using namespace std. // You must use the full name: std::string mystring = "Hello World";
Ниже это список методов String.
length() это один из самых распространенных методов String, он возвращает длину строки (Число знаков строки).
LengthDemo.cpp
#include <iostream> using namespace std; int main() { string str = "This is text"; int len = str.length(); cout << "String Length is : " << len << endl; return 0; }
Результаты запуска примера:

AppendDemo.cpp
#include <iostream> using namespace std; int main() { string s1 = "One"; string s2 = "Two"; string s3 = "Three"; cout << "s1 = " + s1 << endl; cout << "s2 = " + s2 << endl; cout << "s3 = " + s3 << endl; cout << " ------------ " << endl; // Append s2 into s1. string s = s1.append(s2); cout << "s1 = " + s1 << endl; // ==> OneTwo cout << "s = " + s << endl; // ==> OneTwo cout << " ------------ " << endl; // Append s2,s3 into s1. s = s1.append(s2).append(s3); // ==> OneTwoTwoThree cout << "s1.append(s2).append(s3) = " + s << endl; }
Результаты запуска примера:

find is method to find the appear position of a substring in the current string. This method returns the string::npos constant, if not found.

FindDemo.cpp
#include <iostream> using namespace std; int main() { string str = "This is text"; // Find index within this string of the first occurrence 'i'. // ==> 2 string::size_type idx = str.find('i'); cout << "- find('i') = " << idx << endl; // Find index within this string of the first occurrence 'i' // starting the search at index 4. // ==> 5 idx = str.find('i', 4); cout << "- find('i',4) = " << idx << endl; // index within this string of the first occurrence of "te". // ==> 8 idx = str.find("te"); cout << "- find('te') = " << idx << endl; }
Результаты запуска примера:


SubstrDemo.cpp
#include <iostream> using namespace std; int main() { string str = "This is text"; // Returns the substring from index 3 to the end of string. string substr = str.substr(3); cout << "- str.substr(3)=" << substr << endl; // Returns the substring from index 2 to index 7. substr = str.substr(2, 7); cout << "- str.substr(2, 7) =" << substr << endl; }
Результаты запуска примера:

Некоторые методы связаны с заменой.

ReplaceDemo.cpp
#include <iostream> using namespace std; int main() { string str = "This is text"; // Replace the 4-character string starting at position 8 // by "string". string s2 = str.replace(8, 4, "string"); cout << "- str=" << str << endl; // This is string cout << "- s2=" << s2 << endl; // This is string cout << " -------------- " << endl; // Reset str. str = "This is text"; // Replace the 4-character string starting at index 8, // by a substring of another string, 6 characters starting at index 0. // ==> It is string string s3 = str.replace(8, 4, "string is important", 0, 6); cout << "- str=" << str << endl; // It is string cout << "- s3=" + s3 << endl; // It is string cout << " -------------- " << endl; }
Результаты запуска примера:

Пример сочетания find & replace чтобы заменить все определенные подстроки одной новой строкой.
ReplaceAllDemo.cpp
#include <iostream> using namespace std; // A function to find and replace string replaceAll(string subject, const string& search, const string& replace) { size_t pos = 0; // function find return string::npos if not found. while ((pos = subject.find(search, pos)) != string::npos) { subject.replace(pos, search.length(), replace); pos += replace.length(); } return subject; } int main() { string str = "This is text"; cout << "- str: " << str << endl; cout << " --------------------- " << endl; // Find "is" and replace by "???". string result = replaceAll(str,"is", "???"); cout << "- result: " << result << endl; cout << "- str: " << str << endl; }
Запуск примера:

InsertDemo.cpp
#include <iostream> using namespace std; int main() { string str = "This text"; string s2 = str.insert(5, "is "); cout << "- str=" << str << endl; // This is text cout << "- s2=" << s2 << endl; // This is text cout << " -------------- " << endl; }
Запуск примера:

Несмотря на то, что класс string не предоставляет вам метод для конвертации строки в строку с заглавными или строчными буквами, но вы можете это сделать с другими библиотеками в C++.
Используем функцию transform пространства (namespace) с названием std:
UpperLowerDemo1.cpp
#include <iostream> #include <algorithm> #include <string> using namespace std; int main() { string str = "This is text"; cout << "- str= " << str << endl; cout << " ----------------" << endl; // Convert to uppercase std::transform(str.begin(), str.end(),str.begin(), ::toupper); cout << "- str= " << str << endl; // Reset str str = "This is text"; cout << " -------------- " << endl; // Convert to lowercase. std::transform(str.begin(), str.end(),str.begin(), ::tolower); cout << "- str= " << str << endl; }
Запуск примера:
