【C/C++练习题】替换空格

举报
王建峰 发表于 2021/11/19 02:21:41 2021/11/19
【摘要】 《剑指Offer》面试题5   1 问题描述 题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。   2 代码 #include "iostream" using namespace std; //功能:替换字...

《剑指Offer》面试题5

 

1 问题描述

题目:请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。

 

2 代码


  
  1. #include "iostream"
  2. using namespace std;
  3. //功能:替换字符串中的空格
  4. //输入:str字符数组
  5. //返回:true成功
  6. bool ReplaceBlank(char* str, int length)
  7. {
  8. if ((str == nullptr) || (length <= 0))
  9. {
  10. return false;
  11. }
  12. //实际字符串长度和空格数量
  13. int originalLength = 0;
  14. int numberOfBlank = 0;
  15. int i = 0;
  16. while (str[i] != '\0')
  17. {//1.遍历数组,统计字符串实际长度和空格个数
  18. if (str[i] == ' ')
  19. {
  20. numberOfBlank++;
  21. }
  22. originalLength++;
  23. i++;
  24. }
  25. //2.计算新字符串长度
  26. int NewLength = originalLength + numberOfBlank*2;
  27. if (NewLength > length)
  28. {
  29. return false;
  30. }
  31. //3.两个指针,一个指向原字符串尾部,另一个指向新字符串尾部
  32. int OriginIndex = originalLength;
  33. int NewIndex = NewLength;
  34. while ((OriginIndex >= 0) && (NewIndex > OriginIndex))
  35. {//4.从字符串尾部进行操作,从后向前替换
  36. if (str[OriginIndex] == ' ')
  37. {
  38. str[NewIndex--] = '0';
  39. str[NewIndex--] = '2';
  40. str[NewIndex--] = '%';
  41. }
  42. else
  43. {
  44. str[NewIndex--] = str[OriginIndex] ;
  45. }
  46. OriginIndex--;
  47. }
  48. return true;
  49. }
  50. void test01()
  51. {
  52. char str[30] = "hello world !!";
  53. ReplaceBlank(str, sizeof(str)/sizeof(char));
  54. cout << "res:" << str << endl;
  55. }
  56. int main(int argc, char const *argv[])
  57. {
  58. test01();
  59. return 0;
  60. }

 

文章来源: blog.csdn.net,作者:hinzer,版权归原作者所有,如需转载,请联系作者。

原文链接:blog.csdn.net/feit2417/article/details/96691616

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。