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的