下面的代码有什么问题

what is the issue with the below code?

本文关键字:什么 问题 代码      更新时间:2023-10-16

问题是用"%20"替换字符串中包含的空格。所以基本上需要把它插入到一个字符串中,只要有空格。因此,我想用 %20 替换所有空格,但只替换部分字符串。我可以在替换功能中看到正确的 o/p

#include<iostream>
#include<string>
using namespace std;
int spaces(char* s,int size)   /*calculate number of spaces*/
{
    int nspace=0;
    for(int i=0;i<size;i++)
    {
        if(s[i]==' ')
        {
          nspace++;
        }
    }
  return nspace;
}
int len_new_string(char* inp,int l)   /*calculate the length of the new string*/
{
     int new_length=l+spaces(inp,l)*2;
     return new_length;
}
char* replace(char* s,int length)  /*function to replace the spaces within a string*/
{
   int len=len_new_string(s,length);
   char new_string[len];
   int j=0;
   for(int i=0;i<length;i++)
   {
      if(s[i]==' ')     /*code to insert %20 if space is found*/
      {
        new_string[j]='%';
        new_string[j+1]='2';
        new_string[j+2]='0';
        j=j+3;
      }
      else    /*copy the original string if no space*/
      {
         new_string[j]=s[i];
         j++;
      }
   }
 cout<<"Replaced String: "<<new_string<<endl;
 return s=new_string;
 }

int main()
{
  char str[]="abc def ghi ";
  int length=sizeof(str)/sizeof(str[0]);
  cout<<"String is: "<<str<<endl;
  char *new_str=replace(str,length);
  cout<<"Replaced String is: "<<new_str<<endl;
 }

char 数组应该超出范围并被释放。您没有出现段错误的唯一原因是显然没有其他程序在该位置保留内存。为避免这种情况,请尝试使用带填充的 char 数组,通过引用或指针将其交接并填充到位:

void replace(char *in, char *out, size_t length)
{
  /* copy as-is for non-spaces, insert replacement for spaces */
}
int main()
{
  char str[]="abc def ghi";
  size_t buflen(strlen(str)+2*spaces(str, strlen(str)));
  char output[buflen+1];
  memset(output, 0, buflen+1);
  replace(str, output, strlen(str));
}

另一种选择是new[]返回数组(记得事后delete[]它!),或者,我认为您遗漏了某个原因,一直使用std::string以避免数组问题。