如果真的没有什么库函数的话..(最好还是用库函数)
#include
#include
#include
#include
#include
char* replace(const char *src)
{
/* 这个unsigned int相当于char[sizeof(int)] = {'%', '2', '0', .......}; */
unsigned int magic = 0;
magic += (unsigned char)'0';
magic <<= CHAR_BIT;
magic += (unsigned char)'2';
magic <<= CHAR_BIT;
magic += (unsigned char)'%'; // 最低CHAR_BIT位
size_t szall = std::strlen(src); // 字符串总长度
size_t szspace = 0; // 字符串中空格的个数
/* 下面这段代码主要完成空格计数功能 */
unsigned tailInt = ((unsigned int*)src)[szall / sizeof(int)];
size_t szValidCharInTail = szall % sizeof(int);
// before: x .... x ? .... ?
// after: 0 .... 0 x .... x
tailInt >>= ((sizeof(int) - szValidCharInTail) * CHAR_BIT);
while (tailInt != 0)
{
unsigned int ch = tailInt & 0xFF; // 这里假设每个字节8位
if (ch == ' ')
++szspace;
tailInt >>= CHAR_BIT;
}
for (size_t i = 0; i < szall / sizeof(int); ++i)
{
unsigned int v = ((unsigned int*)src)[i];
while (v != 0)
{
unsigned int ch = v & 0xFF; // 这里假设每个字节8位
if (ch == ' ')
++szspace;
v >>= CHAR_BIT;
}
}
char *result = new char[(szall - szspace) + szspace * 3 + 1];
size_t cur = 0;
/* 下面这段代码主要完成空格替换功能 */
for (size_t i = 0; i < szall / sizeof(int); ++i)
{
unsigned int v = ((unsigned int*)src)[i];
while (v != 0)
{
unsigned int ch = v & 0xFF; // 这里假设每个字节8位
if (ch == ' ')
{
unsigned int &v = *(unsigned int*)(&(result[cur]));
v = magic;
cur += 3;
}
else
{
result[cur++] = ch;
}
v >>= CHAR_BIT;
}
}
tailInt = ((unsigned int*)src)[szall / sizeof(int)];
while (tailInt != 0)
{
unsigned int ch = tailInt & 0xFF; // 这里假设每个字节8位
if (ch == ' ')
{
unsigned int &tailInt = *(unsigned int*)(&(result[cur]));
tailInt = magic;
cur += 3;
}
else
{
result[cur++] = ch;
}
tailInt >>= CHAR_BIT;
}
result[cur] = 0;
return result;
}
int main()
{
std::string str;
getline(std::cin, str);
char *result = replace(str.c_str());
std::cout << result;
delete result;
return 0;
}
上面的写法虽然长,看起来也费劲,但是性能较优;但一定不是最优的,因为strlen和空格的检测可以糅合到一起;另外,如果不确定src是四字节对齐的,应该对开头的几个不对齐字节做额外的检测。
先计数主要避免了多次动态内存分配的开销,如果字符串不是大的离谱,因为缓存的原因,计数特别快;每次检测一个INT,对其做4次位检测是很快的,因为4次检测都在寄存器中进行。
不过,这种优化也只是建议性的(也同时展示了C/C++的屌);要真正的优化,还得各种细节,比如,把确定为4次的循环展开等..因此,尽最大的可能使用库,是你的最佳选择,我记得JAVA的String里就有个replace?。