c++ primer 第三章 標準庫類型 string

3.4
#include <iostream>
#include<string>
#include<fstream>
using namespace std;

int main()
{
   string s1,s2;
   getline(cin,s1);
   getline(cin,s2);

   if(s1.size() >= s2.size())
   {
       cout << s1;
   }
   else{
    cout<<s2;
   }
    return 0;
}

3.5

#include <iostream>
#include<string>
#include<fstream>
using namespace std;

int main()
{
   string input,result="";
   while(cin>>input&& input!="#")
   {
       result += input+" ";
   }
   cout<< result;

    return 0;
}

std::toupper()的用法

c++API中提供的

#include <iostream>
#include <cctype>
#include <clocale>
 
int main()
{
    unsigned char c = '\xb8'; // the character ž in ISO-8859-15
                              // but ¸ (cedilla) in ISO-8859-1 
 
    std::setlocale(LC_ALL, "en_US.iso88591");
    std::cout << std::hex << std::showbase;
    std::cout << "in iso8859-1, toupper('0xb8') gives " << std::toupper(c) << '\n';
    std::setlocale(LC_ALL, "en_US.iso885915");
    std::cout << "in iso8859-15, toupper('0xb8') gives " << std::toupper(c) << '\n';
}
Output: 

in iso8859-1, toupper('0xb8') gives 0xb8
in iso8859-15, toupper('0xb8') gives 0xb4

自己寫的例子

#include <iostream>
#include<string>
#include<cctype>

using namespace std;

int main()
{
    string s("hello wprld!!!");
    for(auto &c : s)
    {
        c = toupper(c);
    }
    cout <<s<<endl;
    return 0;
}

output

HELLO WORLD!!!

將第一個單詞大寫

#include <iostream>
#include<string>
#include<cctype>

using namespace std;

int main()
{
  string s ("some string");
  for(decltype(s.size()) index =0;
        index !=s.size() && !isspace(s[index]); ++index)
        {
            s[index] = toupper(s[index]);
        }
    cout << s<<endl;
    return 0;
}
output

SOME string

3.8

#include <iostream>
#include<string>
#include<cctype>

using namespace std;

int main()
{
 string s("12345");
 /*for(auto &c: s)
 {
     c = 'X';
 }
 cout <<s<<endl;
*/
decltype(s.size()) len = 0;
if(!s.empty())
{
    while( len < s.size())
{
        s[len] = 'X';
        len++;
}
}
cout << s<< endl;

    return 0;
}

用while寫麻煩一些,用心時間來說,前者在0.022s左右,後者在0.025s,所以如果數量很大的話,用範圍for要快一些

3.9

在gcc下和在VS2010編譯器下測試都沒有問題,不會報錯

但是根據作者的理論,會出現不可預知錯誤,我猜是c++編譯器給string付了默認的什麼值

所以沒有報錯,但是沒有輸出有說明string是空的???搞不清

搞清了,string有默認初始化,所以在聲明是沒有提供初始化的值,編譯器會將string對象初始化爲空串,

所以沒有報錯,也沒有輸出!~2014、08、22

3.10

#include <iostream>
#include<string>
#include<cctype>

using namespace std;

int main()
{
 string  s = "sfdsdfwe$dasfa&(* HJGHGk  iyt 9uu08duwefrwerw ejhfriweh8&&xiasuhfc\
  wuieha7676tIHauy87^76U6%&%7hu&*&57<daeff.wefwefw,fw.gfdg.dgdt.h";
 if(!s.empty())
 {
        for(auto &c : s)
        {
            if(ispunct(c))
                c = ' ';
        }
 }
 cout << s<< endl;

    return 0;
}

3.11

合法,c爲const char & 類型,截的圖是codeblocks的









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章