C++便利编程的知识点(更新中)

本文介绍了C++中的字符串操作,如单词分割、字符种类判断(包括字母、大小写和标点),以及类型转换(如int转string)、数组初始化、容器(vector)使用、自定义排序函数和数学函数(如取整、平方根和绝对值)。
摘要由CSDN通过智能技术生成

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);

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值