第三章

1.

关于string中是否\0结尾

string:标准中未规定需要\0作为字符串结尾。编译器在实现时既可以在结尾加\0,也可以不加。(因编译器不同)

但是,当通过c_str()或data()(二者在 C++11 及以后是等价的)来把std::string转换为const char *时,会发现最后一个字符是\0。但是C++11,string字符串都是以'\0'结尾。

2.

string s;

s.size()返回值是一个size_type类型。与机器类型无关的无符号类型,不要使用int类型了

 

3.

范围for语句

string str("hello, world");

for(auto c : str)

  cout << c << endl;

 

for(auto &c : str)  //引用

  c = toupper(c);

cout << str << endl;

 

4.二分查找

   while(mid != end && *mid != sought)
   {
           if(sought < *mid)
                   end =mid;
           else
                   beg = mid + 1;
           mid = beg + (end - beg) / 2;
   }

 

 

习题

3.3

类似is >> s的读取:string对象会忽略开头的空白并从第一个真正的字符开始,直到遇见下一空白为止。

类似getline(is, s)的读取:string对象会从输入流中读取字符,直到遇见换行符为止。

3.17

using namespace std;

int main()
{
    vector<string> s;
    string word;

    while(cin >> word)
    {
            s.push_back(word);

    }

    for(auto &word : s)
    {
            for (auto & c : word)
            {
                    c = toupper(c);
            }
    }

    for (auto word : s)
            cout << word << endl;
    return 0;
}

 

posted @ 2021-03-31 15:54  11YS  阅读(38)  评论(0编辑  收藏  举报