char* 函数 返回值使用,ascii码转int组合成的字符串

char* 函数 返回值使用,ascii码转int组合成的字符串
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
using namespace std;

static inline bool get_ascii_string(const string& name, char* get_char) {
    int i = 0, n;
    const char *s = name.c_str();
    char buf[name.length() * 4 ], *p;
    memset(buf, 0, sizeof(buf));
    p = buf;
    for (i = 0; i < strlen(s); i++) {
        n = sprintf(p, "%d", s[i]);
        p += n;
    }
    strcpy(get_char, buf);
    return true;
}

static inline char* new_get_ascii_string(const string& name) {
    int i = 0, n;
    const char *s = name.c_str();
    char* buf = new char[strlen(s) * 4];
    char *p;
    p = buf;
    for (i = 0; i < strlen(s); i++) {
        n = sprintf(p, "%d", s[i]);
        p += n;
    }
    return buf;
}


int main(int argc, char *argv[]) {
    /*
    *这段代码的功能是输入一个字符串test_string 返回这个字符串里面 ascii码对应的int值组成的字符串
    *可以通过这个功能测试char* 函数 返回值的使用
    */
    string test_string = "abcd我";
    for (int i = 0; i < 10; i++) {
        test_string = test_string + "abc";
    }
    cout << "test_string == " << test_string << endl;
    cout<<"test_string.length()="<<test_string.length()<<endl;
    /*这是第一种实现方式*/
    char* test = new char[test_string.length() * 4 ]; //获取的字符串是存放的字符串的 最大数的 4倍
    get_ascii_string(test_string, test);
    cout << "test1 == " << test << endl;
    delete[] test;
    cout << "over1"<<endl;

    /*这是第二种实现方式*/
    char* test2 = new_get_ascii_string(test_string);
    cout << "test2 == " <<test2<< endl;
    delete[] test2;
    cout << "over2"<<endl;


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值