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