#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;
}
char* 函數 返回值使用,ascii碼轉int組合成的字符串
char* 函數 返回值使用,ascii碼轉int組合成的字符串
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.