Строки в C++
Введение | |
Strings | |
substr(): обрезать строку | |
length(): длина строки | |
getline() | |
Другие статьи о C++ |
Введение
В этой статье вы можете изучить примеры работы со строками в C++
Strings
#include <iostream> #include <string> using namespace std; int who_are_you() { string name; cout << "Who are you?" << endl; cin >> name; string greeting = "Hello, " + name; if (name == "Andrei") { greeting += ", I know you!"; } else { greeting += ", nice to meet you!"; } cout << greeting << endl; return 0; } int main() { who_are_you(); return 0; }
Who are you? Andrei Hello, Andrei, I know you!
Who are you? Max Hello, Max, nice to meet you!
Скрипт игнорирует фамилию
Who are you? Winnie Pooh Hello, Winnie, nice to meet you!
substr(): обрезать строку
#include <iostream> #include <string> using namespace std; int main() { string url = "testsetup.ru"; string country = url.substr(10); cout << "country: " << country << endl; return 0; }
country: ru
length(): длина строки
#include <iostream> #include <string> using namespace std; int main() { string url = "testsetup.ru"; string country = url.substr(url.length() - 2); cout << "country: " << country << endl; return 0; }
country: ru
Задача - сравнить два введённых слова и определить какое длиннее.
using namespace std;
int main() {
string word1;
string word2;
cout << "Enter first word" << endl;
cin >> word1;
cout << "Enter 2nd word" << endl;
cin >> word2;
if (word1.length() == word2.length())
{
cout << "words have the same length";
}
if (word1.length() > word2.length())
{
cout << "word1 is longer";
}
if (word1.length() < word2.length())
{
cout << "word2 is longer";
}
return 0;
}
Этот код будет работать только если слово введено без пробелов.
Чтобы сравнивать длины строк воспользуемся getline()
#include <iostream>
#include <string>
using namespace std;
int main() {
string line1;
string line2;
cout << "Enter first word" << endl;
getline(cin , line1);
cout << "Enter 2nd word" << endl;
getline(cin , line2);
if (line1.length() == line2.length())
{
cout << "words have the same length";
}
if (line1.length() > line2.length())
{
cout << "line1 is longer";
}
if (line1.length() < line2.length())
{
cout << "line2 is longer";
}
return 0;
}