질문은 문자열에 포함 된 공백을 "% 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;
}
_ 디버깅 도움말을 찾는 질문 ("이 코드가 작동하지 않는 이유는 무엇입니까?")에는 원하는 동작, 특정 문제 또는 오류 및 질문 자체에서이를 재현하는 데 필요한 가장 짧은 코드가 포함되어야합니다. 분명한 문제 성명이없는 질문은 다른 독자에게 유용하지 않습니다. 참고 : [MCVE]를 만드는 방법 ._ –
로컬 배열에 대한 포인터를 반환하고 있습니다. 'new_string'을 표시하려고하면 이미 사라졌습니다. –