1.string 类
C语言中,字符串是以'\0'结尾的一些字符的集合,为了操作方便,C标准库中提供了一些str系列的库函数,但是这些库函数与字符串是分离开的,不太符合OOP的思想,而且底层空间需要用户自己管理,稍不留神可能还会越界访问。由此引进了string类。
2.auto和范围for
auto的可以使得代码更加简化,auto的用法实例如下:
#include<iostream>
#include <string>
#include <map>
using namespace std;
int main()
{
std::map<std::string, std::string> dict = { { "apple", "苹果" },{ "orange",
"橙子" }, {"pear","梨"} };
// auto的用武之地
//std::map<std::string, std::string>::iterator it = dict.begin();
auto it = dict.begin();
while (it != dict.end())
{
cout << it->first << ":" << it->second << endl;
++it;
}
return 0;
}
auto支持作返回值(慎用)。
范围for的用法示例:
int main()
{
int array[] = { 1, 2, 3, 4, 5 };
// C++98的遍历
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
array[i] *= 2;
}
for (int i = 0; i < sizeof(array) / sizeof(array[0]); ++i)
{
cout << array[i] << endl;
}
// C++11的遍历
for (auto& e : array)
e *= 2;
for (auto e : array)
cout << e << " " << endl;
string str("hello world");
//赋值,自动取容器的数据赋值给左边的值
//自动++,自动判断结束
for (auto ch : str)
{
cout << ch << " ";
}
cout << endl;
return 0;
}
后置追加
int main()
{
string s1("hello");
s1.push_back(',');
s1.push_back('w');
cout << s1 << endl;
s1.append("world");
cout << s1 << endl;
return 0;
}
这段代码的运行结果是:
string的用法较多,具体更多的用法,请参考相关往回走哪,这里不再做叙述。
3.题目练习
class Solution {
public:
bool isLetter(char ch)
{
if (ch >= 'a' && ch <= 'z')
return true;
if (ch >= 'A' && ch <= 'Z')
return true;
return false;
}
string reverseOnlyLetters(string S) {
if (S.empty())
return S;
size_t begin = 0, end = S.size() - 1;
while (begin < end)
{
while (begin < end && !isLetter(S[begin]))
++begin;
while (begin < end && !isLetter(S[end]))
--end;
swap(S[begin], S[end]);
++begin;
--end;
}
return S;
}
};
class Solution {
public:
string addstrings(string num1, string num2)
{
// 从后往前相加,相加的结果到字符串可以使用insert头插
// 或者+=尾插以后再reverse过来
int end1 = num1.size() - 1;
int end2 = num2.size() - 1;
int value1 = 0, value2 = 0, next = 0;
string addret;
while (end1 >= 0 || end2 >= 0)
{
if (end1 >= 0)
value1 = num1[end1--] - '0';
else
value1 = 0;
if (end2 >= 0)
value2 = num2[end2--] - '0';
else
value2 = 0;
int valueret = value1 + value2 + next;
if (valueret > 9)
{
next = 1;
valueret -= 10;
}
else
{
next = 0;
}
//addret.insert(addret.begin(), valueret+'0');
addret += (valueret + '0');
}
if (next == 1)
{
//addret.insert(addret.begin(), '1');
addret += '1';
}
reverse(addret.begin(), addret.end());
return addret;
}
};