场景:
1.在处理手机号码时,往往可能会遇到手机号里有-或,分割,如果去掉这些符号得到一个正常的数字字符串呢?
2.如果不用C++的string,纯C的话估计还得先计算替换后的字符串长度才能开始替换操作吧,其实用stl和C标准库结合实现,只暴露C接口还是比较方便的。没必要局限在只用纯C.
3.如果不想依赖第3放库时怎么办?
删除字符:
wstring ws(L"1-63-42-5 375-2-3"); ws.erase(remove(ws.begin(),ws.end(),L'-'),ws.end()); wcout << "ws: " << ws << endl;
char* ReplaceStr(const char* str, const char* old_flag, const char* new_flag) { std::string new_str(str); size_t old_flag_length = strlen(old_flag); size_t new_flag_length = strlen(new_flag); size_t index = new_str.find(old_flag); while (index != std::string::npos) { new_str.replace(index,old_flag_length,new_flag); index = new_str.find(old_flag,index+new_flag_length); } return strdup(new_str.c_str()); } char* DeleteDelims(const char* str, const char* delims, const char* new_delims) { char* temp = strdup(str); char *result = NULL; result = strtok(temp, delims); std::string new_str; while (result) { new_str.append(result); result = strtok(NULL, delims); if(new_delims && result) { new_str.append(new_delims); } } if(new_str.size()) { return strdup(new_str.c_str()); } return NULL; }
用法:
1.删除字符串里的匹配字符串,删除 - 符号
DeleteDelims("192-2342-2343","-",NULL);
2.替换字符串,把两个空格替换为一个空格.
DeleteDelims("192 2342 2343"," "," ");
const char* str1 = "156-1234-5678"; const char* str2 = "0755-21331234"; const char* str3 = "-0755-21331234"; const char* str4 = "0755-21331234-"; const char* str5 = "-0755-21331234-"; char* str = DeleteDelims(str1, "-", NULL); ASSERT_FALSE(strcmp(str,"15612345678")); free(str); str = DeleteDelims(str2, "-", NULL); ASSERT_FALSE(strcmp(str,"075521331234")); free(str); str = DeleteDelims(str3, "-", NULL); ASSERT_FALSE(strcmp(str,"075521331234")); free(str); str = DeleteDelims(str4, "-", NULL); ASSERT_FALSE(strcmp(str,"075521331234")); free(str); str = DeleteDelims("0755-21331234--", "-", NULL); ASSERT_FALSE(strcmp(str,"075521331234")); free(str); str = ReplaceStr("0755-21331234--", "-", "ab"); ASSERT_FALSE(strcmp(str,"0755ab21331234abab")); free(str); str = ReplaceStr("0755-21331234--", "-", "a-"); ASSERT_FALSE(strcmp(str,"0755a-21331234a-a-")); free(str); str = DeleteDelims(str5, "-", NULL); ASSERT_FALSE(strcmp(str,"075521331234")); free(str); str = DeleteDelims("Name I L", " ", NULL); ASSERT_FALSE(strcmp(str,"NameIL")); free(str); str = DeleteDelims("Name I L", " ", " "); ASSERT_FALSE(strcmp(str,"Name I L")); free(str); str = DeleteDelims("-", "-", NULL); ASSERT_FALSE(str);