本文主要是介绍C++ String16/String8与const char*及char*与vector相互转换(五十一),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1.代码示例
1.String16转const char*
String16 name16 = String16("Hello World");
String8 name8 = String8(name16);
const char *buffer = name8.string();验证:
printf("buffer = %s\n",buffer);注意:
String16.string()其实是const char16_t类型
String8.string()是const char*类型
所以转换之前需要将String16转换成const char*类型
2.char*与vector相互转换
#include <iostream>
#include <vector>
#include <time.h>
#include <string.h>
#include <typeinfo>
using namespace std;int main(){char buffer[] = "123456789";//1.char*(char数组)转vectorvector<char> data(buffer, buffer + strlen(buffer));for(auto d : data)cout << d << "";cout << endl;//2.for循环遍历:vector转charfor(size_t i = 0; i < data.size(); i++){ //data.capacity()添加的容量printf("%c",data[i]);}printf("\n");//3.vector转char*//char *bf = &data.at(0);//安全,有越界检查//char *bf = &data[0];cout << "typeid(data.data()) = " << typeid(data.data()).name() <<endl;printf("data.data() = %s\n",data.data());
}
// vector::data
#include <iostream>
#include <vector>int main (){int size = 10;std::vector<int> myvector(size);int *p = myvector.data();for(int i = 0; i < size; i++)p[i] = i;printf("11 = %ld\n",myvector.size());std::cout << "myvector contains:";for(unsigned i=0; i < myvector.size(); i++)std::cout << ' ' << myvector[i];std::cout << '\n';return 0;
}
Ref
这篇关于C++ String16/String8与const char*及char*与vector相互转换(五十一)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!