C++字符串取单词:
string s= "This is a sample sentence";
// 将字符串传递给 istringstream
istringstream iss(s);
// 存储单词的容器
vector<string> words;
// 逐个读取单词并存储到容器中
string word;
while (iss >> word) {
words.push_back(word);
}
C++判断字符(char)种类:
char ch = 'A'; // 可以是任意字符,包括 Unicode 字符
// 判断是否为字母
if (std::isalpha(ch)) {
std::cout << ch << " is a letter." << std::endl;
}
// 判断是否为大写字母
if (std::isupper(ch)) {
std::cout << ch << " is an uppercase letter." << std::endl;
}
// 判断是否为小写字母
if (std::islower(ch)) {
std::cout << ch << " is a lowercase letter." << std::endl;
}
// 判断是否为标点符号
if (std::ispunct(ch)) {
std::cout << ch << " is a punctuation mark." << std::endl;
}
wchar_t wch = L'你'; // Unicode 字符
// 判断是否为字母或数字(宽字符)
if (std::iswalnum(wch)) {
std::wcout << wch << L" is a letter or digit." << std::endl;
}
// 判断是否为字母(宽字符)
if (std::iswalpha(wch)) {
std::wcout << wch << L" is a letter." << std::endl;
}
// 判断是否为大写字母(宽字符)
if (std::iswupper(wch)) {
std::wcout << wch << L" is an uppercase letter." << std::endl;
}
// 判断是否为小写字母(宽字符)
if (std::iswlower(wch)) {
std::wcout << wch << L" is a lowercase letter." << std::endl;
}
将 int
类型的变量转换为 string
类型:
int num = 123;
string str = to_string(num);
初始化:
数组:
memset(arr, 0, sizeof(arr)); // 将数组 arr 的所有元素设置为 0
函数:void* memset(void* ptr, int value, size_t num);
容器:
vector<int> myVector(5, 10); // 创建一个具有5个元素的vector,每个元素的值都为10
vector排序:
// 自定义比较函数
bool compare(const vector<int>& a, const vector<int>& b) {
return a[0] < b[0];
}
// 对 vec 进行排序
sort(vec.begin(), vec.end(), compare);
大小写转换:
c = toupper(c);
c = tolower(c);
数学相关:
取整并转化形式:
double num = 3.6;
int floorInt = (int)std::floor(num); // 向下取整并转换为整数
int ceilInt = (int)std::ceil(num); // 向上取整并转换为整数
int floorInt = static_cast<int>(std::floor(num)); // 向下取整并转换为整数
int ceilInt = static_cast<int>(std::ceil(num)); // 向上取整并转换为整数
平方根:
sqrt(x);
绝对值:
abs(x);