java替换空格_将一个字符串中的空格替换成“%20”

如果真的没有什么库函数的话..(最好还是用库函数)

#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?。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值