简体   繁体   中英

Replace string spaces with special characters

My program is not replacing every character of special string into the spaces of the input string:

#include <iostream>
#include <string.h>
using namespace std;

char *replacingSpaces(char s[]){

int last = 0, spacecount = 0;

char *sp = (char *) "$99";
int len = (int) strlen(s);
int lensp = (int) strlen(sp);

for(int i = 0;i<len;i++){
    if(s[i]==' ')spacecount++;
}
if(spacecount == 0) return s;

char *newStr = (char *) malloc((size_t) (spacecount*(lensp-1)+len+1));

for(int i = 0;i<len;i++){
    if(s[i]!=' '){
        newStr[last] = s[i];
        last++;

    }
    else{
        newStr[last] = sp[0];
        newStr[last] = sp[1];
        newStr[last] = sp[2];
        last++;

    }
 }
 newStr[last++] = '\0';


 return newStr;
 }

 int main(){

 char s[100] = "Replace spaces with special characters";
 cout << replacingSpaces(s) << endl;

 return 0;
 }

and the output of the program is as follows:

Replace9spaces9with9special9characters

Thank you in advance.

I think the problem is in you increment operator last++ , You have to increment it inside newStr[last] :

for(int i = 0;i<len;i++){
    if(s[i]!=' '){
        newStr[last++] = s[i];


    }
    else{
        newStr[last++] = sp[0];
        newStr[last++] = sp[1];
        newStr[last++] = sp[2];

    }
 }

and why so many casts?

Try this ...

else{
    newStr[last++] = sp[0];
    newStr[last++] = sp[1];
    newStr[last++] = sp[2];
}

It should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM