初始化string对象
#include <string>
using namespace::std;
int main()
{
string s1;
string s2 = s1;
string s2(s1);
string s3 = "hiya";
string s3("hiya");
string s4(10, 'c');
}
string对象上的操作
#include <string>
#include <iostream>
using namespace::std;
int main()
{
string s;
cin >> s;
cout << s << endl;
string s1, s2;
cin >> s1 >> s2;
cout << s1 << s2 << endl;
string word;
while (cin >> word)
cout << word << endl;
string line;
while (getline(cin, line))
if(line.size() > 80)
cout << line << endl;
string slang1 = "hello";
string slang2 = "hiya";
if (slang1 < slang2);
string str1 = "hey";
string str2 = "heyyyy";
if (str1 < str2);
string st1(10, 'c'), st2;
st1 = st2;
string s1 = "hello, ", s2 = "world.\n";
string s3 = s1 + s2;
s1 += s2;
string s4 = "hello " + "," + s2;
return 0;
}
练习
#include <string>
#include <iostream>
using namespace::std;
void a() {
string str;
while(1)
getline(cin, str);
}
void b() {
string str;
while (1)
cin >> str;
}
void c() {
string str1, str2;
if (str1 == str2)
cout << " str1 equal to str2" << endl;
else {
cout << "no equal" << endl;
if (str1 > str2)
cout << str1 << endl;
else
cout << str2 << endl;
}
}
void d() {
string str1, str2;
if (str1.size() == str2.size())
cout << "str1和str2等长" << endl;
else {
if (str1.size() > str2.size())
cout << str1 << endl;
else
cout << str2 << endl;
}
}
void e() {
string word, phrase;
while (cin >> word) {
phrase += word;
}
cout << phrase << endl;
}
void f() {
string word, phrase;
while (cin >> word) {
cout << word << " " << endl;
}
}
处理string对象中的字符
#include <iostream>
#include <string>
#include <cctype>
#include <Windows.h>
using namespace::std;
int main()
{
string str("some string");
for (auto c : str) {
Sleep(200);
cout << c << endl;
}
cout << endl;
string s("Hello ECNU Software Engineering Institute");
for (auto c : s) {
Sleep(200);
cout << c << endl;
}
auto upper_cnt = 0;
for (auto c : s)
if (isupper(c))
upper_cnt++;
cout << upper_cnt << endl;
for (auto &c : s)
c = toupper(c);
cout << s << endl;
string s2("hi ecnu ");
if (!s2.empty())
s[0] = toupper(s[0]);
for (decltype(s2.size()) index = 3;
index != s2.size() && !isspace(s[index]); ++index)
s[index] = toupper(s[index]);
const string hexdigits = "0123456789ABCDEF";
cout << "输入十进制数:";
string result;
string::size_type n;
while (cin >> n)
if (n < hexdigits.size())
result += hexdigits[n] + " ";
cout << "转换成十六进制数为:" << result << endl;
}
练习
#include<iostream>
#include<string>
#include<cctype>
using namespace::std;
int main()
{
string s1("Tomorrow is 520");
for (auto &c : s1)
c = 'X';
cout << s1 << endl;
for (char &c : s1)
c = 'O';
cout << s1 << endl;
auto i = 0;
for (i = 0; i < s1.size(); i++)
s1[i] = 'X';
i = 0;
while (i < s1.size())
{
s1[i] = 'X';
i++;
}
string s;
if(!s.empty())
cout << s[0] << endl;
string ss1, ss2;
getline(cin, ss1);
for (auto c : ss1)
{
if (!ispunct(c))
ss2 += c;
}
cout << ss2 << endl;
const string sss = "Keep out!";
for (auto &c : s) {
}
return 0;
}