一个完整,c++实现js.escape的代码片段
string& js_escape(string &str) { setlocale(LC_CTYPE,""); wchar_t aa[1<<10]; mbstowcs(aa,str.c_str(),str.size()); wstring wcs(aa); str = ""; for(int i=0;i<wcs.size();i++) { if(wcs[i]>0xff) { char tmp[5]; sprintf(tmp,"%x",wcs[i]); str += "%u"; str += tmp; } else { if( (wcs[i]>='a' && wcs[i]<='z') || (wcs[i]>='A' && wcs[i]<='Z') || ( wcs[i]>='0' && wcs[i]<='9' ) ) { char tmp[2]; sprintf(tmp,"%c",wcs[i]); str += tmp; } else { char tmp[3]; sprintf(tmp,"%02x",wcs[i]); str += "%"; str += tmp; } } } return str; } int main() { string str = "冯a继b业"; string ss = js_escape(str); cout << ss << endl; return 0; }