[Pratice]欺骗_库函数

本文介绍了使用C++进行字符串操作的实用技巧,包括如何利用strcpy和strlen实现strcat功能,以及从字符串中提取数字的不同方法。通过具体示例展示了直接内存拷贝与使用atoi函数的两种常见做法。


先来一个有意思的例子。

用strcpy和strlen实现strcat


#include <cstring>
#include <iostream>
using namespace std;

//直接把c1字符串后面的内存空间覆盖,
//有影响其他数据的风险
void my_strcat(char c1[], const char c2[])
{
    strcpy( (c1 + strlen(c1) ), c2);
}

int main(int argc, char const *argv[])
{
    char hehe[] = "fuck ";
    my_strcat(hehe, "you");
    cout << hehe;
    return 0;
}

以 从字符串中提取数字 为例?
#include <iostream>
#include <cstring>
using namespace std;

template <typename T>
void print(T* p)
{
    int k = 0;
    for (int i = 0; p[i]; ++i)
    {
        cout << p[i];
        ++k;
        if (k % 10)
            cout << " ";
        else 
            cout << endl;
    }
}

bool isDigit(const char& ch) 
{
    return (ch >= '0' && ch<= '9');
}


int main(int argc, char const *argv[])
{
    char c[100] = {0};
    int extract[100] = {0};
    int num = 0, temp = 0;
    cin.getline(c, 100);
    for (unsigned int i = 0; i < strlen(c); )
    {
        if (isDigit(c[i]) )
        {
            while(isDigit(c[i]) )
            {
                temp = temp * 10 + c[i] - '0';
                ++i;
            }
            extract[num] = temp;
            ++num;
            temp = 0;
            continue;
        }
        ++i;
    }
    print<int>(extract);
    return 0;
}
以上是比较常规的做法,前一位X10 + 后一位。


以下利用atoi这个库函数(有些编译器没这函数。)

大致做法:记录 数字 和非数字的 分界点,用atoi将其转化。

#include <iostream>
#include <cstring>
using namespace std;

template <typename T>
void print(T* p)
{
    int k = 0;
    for (int i = 0; p[i]; ++i)
    {
        cout << p[i];
        ++k;
        if (k % 10)
            cout << " ";
        else 
            cout << endl;
    }
}

bool isDigit(const char& ch) 
{
    return (ch >= '0' && ch<= '9');
}


int main(int argc, char const *argv[])
{
    char c[100] = {0};
    int extract[100] = {0};
    int num = 0, temp = 0;
    cin.getline(c, 100);
    for (unsigned int i = 0; i < strlen(c); )
    {
        if (isDigit(c[i]) )
        {
            while(isDigit(c[i]) )
            {
                temp = temp * 10 + c[i] - '0';
                ++i;
            }
            extract[num] = temp;
            ++num;
            temp = 0;
            continue;
        }
        ++i;
    }
    print<int>(extract);
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值