1.函数名: tolower
功 能: 把字符转换成小写字母,非字母字符不做出处理
例题:acwing768题
//方法1:使用tolower函数
#include<bits/stdc++.h>
using namespace std;
int main(void)
{
string a,b;
getline(cin,a);
getline(cin,b);
for(auto &c:a) c = tolower(c);
for(auto &c:b) c = tolower(c);
if(a == b) cout << '=';
if(a > b) cout << '>';
if(a < b) cout << '<';
}
//方法2;普通做法
#include <bits/stdc++.h>
int main(void)
{
char a[100], b[100];
fgets(a, 100, stdin);
fgets(b, 100, stdin);
if (a[strlen(a) - 1] == '\n') a[strlen(a) - 1] = 0; // 去掉末尾回车
if (b[strlen(b) - 1] == '\n') b[strlen(b) - 1] = 0;
for (int i = 0; a[i]; i ++ )
if (a[i] >= 'A' && a[i] <= 'Z')
a[i] += 32;
for (int i = 0; b[i]; i ++ )
if (b[i] >= 'A' && b[i] <= 'Z')
b[i] += 32;
int t = strcmp(a, b);
if (t == 0) puts("=");
else if (t < 0) puts("<");
else puts(">");
}
2.函数名: stringstream
功能:通过字符串中的空格将字符串分隔开,从而成为几个独立的部分
详细用法如下:
stringstream 实现字符串分隔
C++ stringstream的用法:用stringstream来实现任意类型之间的转换,用来巧妙解竞赛问题。
例题如下:acwing770题
//方法1;使用stringstream
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
string s, a, b;
getline(cin, s);
cin >> a >> b;
stringstream ssin(s);
string str;
while (ssin >> str)
{
if (str == a) cout << b << ' ';
else cout << str << ' ';
}
return 0;
}
//方法2:普通做法
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
string s,a,b;
getline(cin,s);
cin>>a>>b;
for(int i=0;i<s.size();i++)
{
string word;
while(i<s.size()&&s[i]!=' ') word+=s[i++];
if(word==a) cout<<b<<" ";
else cout<<word<<" ";
}
}
3.函数名:unique()
unique()是C++标准库函数里面的函数,其功能是去除相邻的重复元素(只保留一个),所以使用前需要对数组进行排序,对于长度为n的数组a,unique(a,a+n) - a返回的是去重后的数组长度,不过,它并没有将重复的元素删除,有很多文章说的是,unique去重的过程是将重复的元素移到容器的后面去,实际上这种说法并不正确,应该是把不重复的元素移到前面来。
例图如下:
例题如下:acwing817题
//去重函数unique()
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
int n,s[1010];
cin>>n;
for(int i=0;i<n;i++)
cin>>s[i];
sort(s,s+n);
int t=unique(s,s+n)-s;
cout<<t;
}
4.函数名:substr()
用法:substr有2种用法。假设:string s = “0123456789”;
string a = s.substr(6); //只有一个数字6表示从下标为6开始一直到结尾:a = “6789”。
string b = s.substr(5, 3); //从下标为5开始截取长度为3位:b = “567”
例题如下:acwing773题
//方法1:使用substr()函数
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
string a,b;
while (cin>>a>>b)
{
int p=0;
for (int i=1;i<a.size();i++)
if (a[i]>a[p])
p=i;
cout<<a.substr(0, p+1)+b+a.substr(p+1)<<endl;
}
return 0;
}
//方法2:普通做法
#include <bits/stdc++.h>
using namespace std;
int main(void)
{
string a,b;
while(cin>>a>>b)
{
int t=0;
char c='0';
for(int i=0;i<a.size();i++)
{
if(a[i]>c) c=a[i];
}
for(int i=0;i<a.size();i++)
{
cout<<a[i];
if(a[i]==c&&t==0)
{
cout<<b;
t=1;
}
}
cout<<endl;
}
}