竞赛技巧之字符串处理初探(一)
作者:冷萃泡泡茶
摘要:本文简要叙述了如何在竞赛中处理字符串,具体方式是通过引入C++ STL中的String类。
字符串的定义与初始化
出于提高效率的目的,我们不从类与对象的角度来理解这件事情。
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string str1 = "Hello";
string str2 = "World";
string str3;
int len ;
// 复制 str1 到 str3
str3 = str1;
cout << "str3 : " << str3 << endl;
// 连接 str1 和 str2
str3 = str1 + str2;
cout << "str1 + str2 : " << str3 << endl;
// 连接后,str3 的总长度
len = str3.size();
cout << "str3.size() : " << len << endl;
return 0;
}
输出结果:
str3 : Hello
str1 + str2 : HelloWorld
str3.size() : 10
to_string()
前置条件:#include
功能:将数字常量转换为字符串
参数:value
返回值:转换好的字符串
定义于头文件
std::string to_string(int value); (1) (C++11起)
std::string to_string(long value); (2) (C++11起)
std::string to_string(long long value); (3) (C++11起)
std::string to_string(unsigned value); (4) (C++11起)
std::string to_string(unsigned long value); (5) (C++11起)
std::string to_string(unsigned long long value); (6) (C++11起)
std::string to_string(float value); (7) (C++11起)
std::string to_string(double value); (8) (C++11起)
std::string to_string(long double value); (9) (C++11起)
示例程序:
#include <iostream> // std::cout
#include <string> // std::string, std::to_string
using namespace std ;
int main()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1 + 2 + 4 + 7 + 14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
}
输出结果:
pi is 3.141593
28 is a perfect number
count()
count 是 algorithm 库中的一个函数,利用迭代器的帮助来计算某个容器中某成员出现的个数。
string mainString = "Let life be beautiful like summer flowers,death like autumn leaves";
int total = count(mainString.begin(), mainString.end(), 'u');
cout << "this char total is " << total << endl;
结果:
输出:this char total is 5
vector<int> countArray = { 1, 3, 2, 3, 4 ,3 ,2, 2, 2 };
int toalNum = count(countArray.begin(), countArray.end(), 2);
cout << "toal: " << toalNum << endl;
输出结果 total:4
万能头文件(谨慎使用)
#include<bits/stdc++.h>