21xrx.com
2024-09-20 01:06:16 Friday
登录
文章检索 我的文章 写文章
C++实现空格替换
2023-07-05 08:15:53 深夜i     --     --
C++ 空格 替换 字符串 算法

空格替换是字符串处理中常见的操作之一。在C++语言中,字符串可以使用字符数组或者字符串对象进行表示。对于字符数组,我们可以使用循环遍历,并通过条件语句对空格进行判断和替换;对于字符串对象,可以使用replace()函数进行替换操作。

方法一:使用字符数组实现

代码如下:


#include <iostream>

#include <cstring>

using namespace std;

void replaceSpace(char *str,int length) {

  int spaceCount = 0;

  // 统计空格的数量

  for(int i = 0; i < length; i++){

    if(str[i] == ' '){

      spaceCount++;

    }

  }

  // 计算替换后的字符数组长度

  int newLength = length + spaceCount * 2;

  char* newStr = new char[newLength + 1];

  // 从后向前填充字符数组

  newStr[newLength] = '\0';

  for(int i = length-1, j = newLength-1; i >= 0 && j >= 0; i--){

    if(str[i] == ' '){

      newStr[j--] = '0';

      newStr[j--] = '2';

      newStr[j--] = '%';

    }else{

      newStr[j--] = str[i];

    }

  }

  // 将新字符数组赋值给原字符数组

  strncpy(str, newStr, newLength);

  delete[] newStr;

}

int main()

{

  char str[20] = "C++ is best";

  replaceSpace(str, strlen(str));

  cout << str << endl;

  return 0;

}

运行结果:C++%20is%20best

方法二:使用字符串对象实现

代码如下:


#include <iostream>

#include <string>

using namespace std;

string replaceSpace(string str) {

  string newStr = "";

  for(int i = 0; i < str.size(); i++){

    if(str[i] == ' '){

      newStr += "%20";

    }else{

      newStr += str[i];

    }

  }

  return newStr;

}

int main()

{

  string str = "C++ is best";

  str = replaceSpace(str);

  cout << str << endl;

  return 0;

}

运行结果:C++%20is%20best

综上所述,C++实现空格替换有多种方式,选择不同的方式需要根据具体的场景和需求进行权衡。无论使用哪种方式实现,都需要考虑到字符数组长度的调整和新旧字符数据的转换等关键问题。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复